Subclassing Python dictionary to override __setitem__

I’m answering my own question, since I eventually decided that I really do want to subclass Dict, rather than creating a new mapping class, and UserDict still defers to the underlying Dict object in some cases, rather than using the provided __setitem__. After reading and re-reading the Python 2.6.4 source (mostly Objects/dictobject.c, but I grepped … Read more

Subclass dict: UserDict, dict or ABC?

If you want a custom collection that actually holds the data, subclass dict. This is especially useful if you want to extend the interface (e.g., add methods). None of the built-in methods will call your custom __getitem__ / __setitem__, though. If you need total control over these, create a custom class that implements the collections.MutableMapping … Read more

Swift + CoreData: Cannot Automatically Set Optional Attribute On Generated NSManagedObject Subclass

The optional checkbox in the Core Data Model Editor has been existing before Swift and its optionals where introduced. Apple states about it in its Core Data Programming Guide: You can specify that an attribute is optional — that is, it is not required to have a value. In general, however, you are discouraged from … Read more

Why doesn’t a using-declaration work to solve the diamond problem?

Someone else can find the standard quote but I’m going to explain conceptually. It doesn’t work because a using-declaration only affects name lookup. Your using-declaration causes name lookup to succeed where it would otherwise fail, that is, it tells the compiler where to find the function f. But it does not tell it which A … Read more

Reclassing an instance in Python

Reclassing instances like this is done in Mercurial (a distributed revision control system) when extensions (plugins) want to change the object that represent the local repository. The object is called repo and is initially a localrepo instance. It is passed to each extension in turn and, when needed, extensions will define a new class which … Read more

Subclassing tuple with multiple __init__ arguments

Because tuples are immutable, you have to override __new__ instead: python docs object.__new__(cls[, …]) Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are … Read more