Basically this started with my problem that I had when trying to find if the index exist in a dict:
if collection[ key ]: # if exist
#do this
else: # if no exist
#do this
But when the index really doesn’t exist it throws me a KeyError.
So, reading the Python documentation. If the missing() is defined it will not throw the KeyError.
collection = {}
def collection.__missing__():
return false
The above code on the terminal gives me:
ghelo@ghelo-Ubuntu:~/Music$ python __arrange__.py
File "__arrange__.py", line 16
def allArts.__missing__():
^
SyntaxError: invalid syntax
So, how to do this correctly?
Btw, I’ll be needing to use Python 2.7 on this. And is there a difference when running on Python 3?
This is how you do it:
or, as suggested by @sdolan, you can use the
.getmethod, which returs a default (optional second parameter) if it does not exist.If you want to use
__missing__you would apply it to a class that extends dict (in this case):OUTPUT