Utility Classes :: HasAttr
HasAttr() is used when you don't care about the type of the object, per se, only that it implements a given interface.
@accepts(HasAttr(['foo', 'bar'])
In order for an object to pass the above signature, it must have both a foo and bar attribute, regardless of what type they are.
The following signature requires that the object have foo and bar attribute, both of which must be ints.
@accepts(HasAttr({'foo':int, 'bar':int})
These two modes of expression, named and typed, can be mixed.
The following signature requires that the object have a foo attribute, which may be of any type, and a bar attribute, which must be callable:
@accepts(HasAttr(['foo'], {'bar': IsCallable()})
Note that if you specify the same attribute in both the named and typed modes, as in the following example, the typed mode will take precedence:
HasAttr(['foo', 'bar']. {'foo': IsCallable()})
is equivalent to
HasAttr(['bar']. {'foo': IsCallable()})
Details
The
HasAttr()constructor accepts either one or two parameters. You may supply a list of strings, a string-keyed dictionary, or both; to supply more arguments will raise aTypeError.It is illegal to pass two lists or two dictionaries to the
HasAttr(); to do this will raise aTypeErrorInstances of
HasAttrwill compare (==) and hash equally if they match the same interface. Coercion as outlined above must be taken into account. Even though the following two instances were passed different arguments, they match the same interface and therefore compare equal:HasAttr(['foo', 'bar']. {'foo': IsCallable()})HasAttr(['bar']. {'foo': IsCallable()})If the checked object lacks an attribute specified in the
HasAttr-defined interface, theHasAttrinstance's__typecheck__will raise a_TC_MissingAttrErrorwith the name of the missing attribute. This exception is to be caught and converted to aTypeCheckErrorbefore it reaches the user.If an attribute of the checked object does not match the asserted conditions, the
HasAttrinstance's__typecheck__will raise a_TC_AttrErrorwith the expected type and the name of the offending attribute. This exception is to be caught and converted to aTypeCheckErrorbefore it reaches the user.