pyramid.utils.if_has_delegate

pyramid.utils.if_has_delegate(delegate)[source][source]

Wrap a delegated instance attribute function.

Creates a decorator for methods that are delegated in the presence of a results wrapper. This enables duck-typing by hasattr returning True according to the sub-estimator.

This function was adapted from scikit-learn, which defines if_delegate_has_method, but operates differently by injecting methods not based on method presence, but by delegate presence.

Parameters:

delegate : string, list of strings or tuple of strings

Name of the sub-estimator that can be accessed as an attribute of the base object. If a list or a tuple of names are provided, the first sub-estimator that is an attribute of the base object will be used.

Examples

>>> from pyramid.utils.metaestimators import if_has_delegate
>>>
>>> class A(object):
...     @if_has_delegate('d')
...     def func(self):
...         return True
>>>
>>> a = A()
>>> # the delegate does not exist yet
>>> assert not hasattr(a, 'func')
>>> # inject the attribute
>>> a.d = None
>>> assert hasattr(a, 'func') and a.func()