python - How to make __missing__ automatically called on __getitem__ KeyError -


i'm writing class emulates mapping object. has following functions.

class myclass(object):     def __init__(self):         self.vars = {}      def __getitem__(self,key):         return self.vars[key]      def __missing__(self,key):         return key 

i think call obj[missing_key] call __missing__. since i've overridden __getitem__ have this

def __getitem__(self,key):     try:         return self.vars[key]     except keyerror e:         return self.__missing__(key) 

it seems __missing__ hook not wrapped calls __getitem__ instead built inside __getitem__. makes __missing__ hook useful classes extend dict. in case makes no sense , should implement missing functionality inside try/except.

is there way make __getitem__ automatically call __missing__ on keyerror?

per the docs:

object.__missing__(self, key)

called dict.__getitem__() implement self[key] dict subclasses when key not in dictionary.

basically, if you're not dict subclass, or are, overloaded __getitem__ without delegating inheritance chain dict.__getitem__, __missing__ means nothing, because nothing checks it. you can't make call __missing__ implicitly unless you're dict subclass.

if you're writing own mapping class, , want __missing__, don't need have __missing__ @ all, put handling code in __getitem__:

def __getitem__(self, key):     try:         return self.var[key]     except keyerror:         return key 

that behaves way expected (note: not update self.var). use dict.get shorten just:

def __getitem__(self, key):     return self.var.get(key, key) 

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -