Is there a consensus on how to check a polymorphic instance?

Steven Bethard steven.bethard at gmail.com
Tue Nov 23 07:31:16 CET 2004


Mike Meng wrote:
> 1. In `Text Processing in Python', David Mertz suggests using `hasattr'
> to check abilities instead of type checking.

hasattr can give you problems if the attribute you're checking for is 
calculated on the fly since hasattr basically does the same thing 
getattr does:

 >>> class C(object):
...     def time():
...         def fget(self):
...             time.sleep(5)
...             return time.time()
...         return dict(fget=fget)
...     time = property(**time())
...
 >>> c = C()
 >>> hasattr(c, 'time')
True
 >>> c.time
1101191279.3729999

If you run the code above, you'll get the 5 second pause both during the 
hasattr call and the c.time access.  If any object you use calculates 
attribute values on the fly, calling hasattr before directly accessing 
the attribute will cause the value to be calculated twice.

Steve



More information about the Python-list mailing list