hasattr

How to test if python class parent has method defined?

How to test if python class parent has method defined? Question: I have a subclass that may have a method ‘method_x’ defined. I want to know if ‘method_x’ was defined somewhere else up the class hierarchy. If I do: hasattr(self, ‘method_x’) I’ll get a truth value that also looks at any methods defined for the …

Total answers: 2

Python's hasattr on list values of dictionaries always returns false?

Python's hasattr on list values of dictionaries always returns false? Question: I have a dictionary that sometimes receives calls for non-existent keys, so I try and use hasattr and getattr to handle these cases: key_string = ‘foo’ print “current info:”, info print hasattr(info, key_string) print getattr(info, key_string, []) if hasattr(info, key_string): array = getattr(info, key_string, …

Total answers: 6

hasattr() vs try-except block to deal with non-existent attributes

hasattr() vs try-except block to deal with non-existent attributes Question: if hasattr(obj, ‘attribute’): # do somthing vs try: # access obj.attribute except AttributeError, e: # deal with AttributeError Which should be preferred and why? Asked By: Imran || Source Answers: The first. Shorter is better. Exceptions should be exceptional. Answered By: Unknown hasattr internally and …

Total answers: 12

Checking for member existence in Python

Checking for member existence in Python Question: 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 …

Total answers: 5