Next / Previous / Contents / TCC Help System / NM Tech homepage

21.10. hasattr(): Does a value have an attribute of a given name?

This predicate tests to see if some instance I has an attribute whose name is given by some string s:

hasattr(I, s)

If this function returns True, you can be sure that the instance has an attribute named s. However, if it returns False, attempts to access an attribute may still succeed, if the class provides dynamic attributes; see Section 26.3.14, “__getattr__(): Handle a reference to an unknown attribute”. Example:

>>> class C:
...     def __init__(self, disc):
...         self.disk = disc
... 
>>> c=C('five')
>>> hasattr(c, 'disk')
True
>>> hasattr(c, 'disc')
False
>>> hasattr(c, 'jukebox')
False
>>> c.jukebox = 'Nine'
>>> hasattr(c, 'jukebox')
True