I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use hasattr like this:
class Foo(object):
@classmethod
def singleton(self):
if not hasattr(self, 'instance'):
self.instance = Foo()
return self.instance
But ...
if hasattr(obj, 'attribute'):
# do somthing
vs
try:
# access obj.attribute
except AttributeError, e:
# deal with AttributeError
Which should be preferred and why?
...
At runtime, the Python code gets the name of a submodule to load, which I don't know before. Now, I want to check, if this submodule exists inside an existing module. Consider this structure, where foo and bar can be specified:
master/
|
|- __init__.py
|
|- foo/
| |
| |- __init__.py
|
|- bar/
|
|- __init__.py
Now, usually I do...