Is there a consensus on how to check a polymorphic instance?
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
>>> class C(object):
... def time():
... def fget(self):
... return time.time()
... return dict(fget=fget)
... time = property(**time())
>>> c = C()
>>> hasattr(c, 'time')
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.
More information about the Python-list