I've created a subclass of dict as per this question. What I'd like to do is be able to create a new dictionary of my subclass by using bracket notation. Namely, when I have {"key":"value"}, I'd like it to call mydict(("key","value")). Is this possible?
Asked
Active
Viewed 205 times
1
-
1No. And for good reasons: it would violate the expectations of people reading the code. – Jared Smith Nov 01 '18 at 17:17
1 Answers
4
No. And for good reasons: it would violate the expectations of people reading the code. It would also likely break any third-party libraries that you import which would (reasonably) expect dict literals to be standard python dictionaries.
A better method to fix this without lots of extra typing is to simply add a static .from
method on your custom dictionary class that attempts to consume the literal and returns an instance of your custom dictionary.
MyDict.from({
"key": "value"
})
Where an implementation of from
might look something like
@classmethod
def from(cls, dictionary):
new_inst = cls()
for key, value of dictionary.items():
new_inst[key] = value
return newInst
Edit based on comment:
user2357112 correctly points out that you could just use the constructor as long as the dict constructor's signature is the same as your custom class:
some_instance = MyDict({"key": "value"})
If you've messed with it though you'll have to go the custom route a la from
.

Jared Smith
- 19,721
- 5
- 45
- 83
-
2For a dict subclass with the "usual" signature, that `from` method would be pointless; just using the constructor would do the same job. (For a dict subclass with a different signature, it's likely that such a `from` method wouldn't have enough information to construct an instance, because it's missing whatever information is in the normal constructor arguments.) – user2357112 Nov 01 '18 at 17:26
-
@user2357112 edited to include your point. However in the case where the signature is modified you'd just have to add the appropriate parameters to the definition of `from`. – Jared Smith Nov 01 '18 at 17:32