API documentation¶
The following API documentation was automatically generated from the source code of property-manager 3.0:
property_manager¶
Useful property variants for Python programming.
Introduction¶
The property_manager module defines several property variants
that implement Python’s descriptor protocol to provide decorators that turn
methods into computed properties with several additional features.
Custom property types¶
Here’s an overview of the predefined property variants and their supported operations:
| Variant | Assignment | Reassignment | Deletion | Caching |
|---|---|---|---|---|
custom_property |
No | No | No | No |
writable_property |
Yes | Yes | No | No |
mutable_property |
Yes | Yes | Yes | No |
required_property |
Yes | Yes | No | No |
key_property |
Yes | No | No | No |
lazy_property |
No | No | No | Yes |
cached_property |
No | No | Yes | Yes |
If you want a different combination of supported options (for example a cached
property that supports assignment) this is also possible, please take a look at
custom_property.__new__().
The following inheritance diagram shows how the predefined property
variants relate to each other:

The property manager superclass¶
In addition to these property variants the property_manager
module also defines a PropertyManager class which implements several
related enhancements:
- Keyword arguments to the constructor can be used to set writable properties
created using any of the
propertyvariants defined by theproperty_managermodule. - Required properties without an assigned value will cause the constructor
to raise an appropriate exception (
TypeError). - The
repr()ofPropertyManagerobjects shows the names and values of all properties. Individual properties can be omitted from therepr()output by setting thereproption toFalse.
Logging¶
The property_manager module emits log messages at the custom log level
SPAM which is considered more verbose than DEBUG, so if you want these messages to be logged make sure they’re not
being ignored based on their level.
Classes¶
-
property_manager.SPHINX_ACTIVE= True¶ Truewhen Sphinx is running,Falseotherwise.We detect whether Sphinx is running by checking for the presence of the ‘sphinx’ key in
sys.modules. The result determines the default value ofUSAGE_NOTES_ENABLED.
-
property_manager.USAGE_NOTES_VARIABLE= 'PROPERTY_MANAGER_USAGE_NOTES'¶ The name of the environment variable that controls whether usage notes are enabled (a string).
-
property_manager.USAGE_NOTES_ENABLED= True¶ Trueif usage notes are enabled,Falseotherwise.This defaults to the environment variable
USAGE_NOTES_VARIABLE(coerced usingcoerce_boolean()) when available, otherwiseSPHINX_ACTIVEdetermines the default value.Usage notes are only injected when Sphinx is running because of performance. It’s nothing critical of course, but modifying hundreds or thousands of docstrings that no one is going to look at seems rather pointless :-).
-
property_manager.NOTHING= <object object>¶ A unique object instance used to detect missing attributes.
-
property_manager.set_property(obj, name, value)[source]¶ Set or override the value of a property.
Parameters: - obj – The object that owns the property.
- name – The name of the property (a string).
- value – The new value for the property.
This function directly modifies the
__dict__of the given object and as such it avoids any interaction with object properties. This is intentional:set_property()is meant to be used by extensions of the property-manager project and by user defined setter methods.
-
property_manager.clear_property(obj, name)[source]¶ Clear the assigned or cached value of a property.
Parameters: - obj – The object that owns the property.
- name – The name of the property (a string).
This function directly modifies the
__dict__of the given object and as such it avoids any interaction with object properties. This is intentional:clear_property()is meant to be used by extensions of the property-manager project and by user defined deleter methods.
-
property_manager.format_property(obj, name)[source]¶ Format an object property’s dotted name.
Parameters: - obj – The object that owns the property.
- name – The name of the property (a string).
Returns: The dotted path (a string).
-
class
property_manager.PropertyManager(**kw)[source]¶ Optional superclass for classes that use the computed properties from this module.
Provides support for required properties, setting of properties in the constructor and generating a useful textual representation of objects with properties.
Here’s an overview of the
PropertyManagerclass:Superclass: objectSpecial methods: __eq__(),__ge__(),__gt__(),__hash__(),__init__(),__le__(),__lt__(),__ne__()and__repr__()Public methods: clear_cached_properties(),find_properties(),have_property(),render_properties()andset_properties()Properties: key_properties,key_values,missing_properties,repr_propertiesandrequired_properties-
__init__(**kw)[source]¶ Initialize a
PropertyManagerobject.Parameters: kw – Any keyword arguments are passed on to set_properties().
-
set_properties(**kw)[source]¶ Set instance properties from keyword arguments.
Parameters: kw – Every keyword argument is used to assign a value to the instance property whose name matches the keyword argument. Raises: TypeErrorwhen a keyword argument doesn’t match apropertyon the given object.
-
key_values¶ A tuple of tuples with (name, value) pairs for each name in
key_properties.
-
missing_properties¶ The names of key and/or required properties that are missing.
This is a list of strings with the names of key and/or required properties that either haven’t been set or are set to
None.
-
repr_properties¶ The names of the properties rendered by
__repr__()(a list of strings).When
key_propertiesis nonempty the names of the key properties are returned, otherwise a more complex selection is made (of properties defined by subclasses ofPropertyManagerwhosereprisTrue).
-
find_properties(**options)[source]¶ Find an object’s properties (of a certain type).
Parameters: options – Passed on to have_property()to enable filtering properties by the operations they support.Returns: A sorted list of strings with the names of properties.
-
have_property(name, **options)[source]¶ Check if the object has a property (of a certain type).
Parameters: Returns: Trueif the object has a property with the expected options enabled/disabled,Falseotherwise.
-
render_properties(*names)[source]¶ Render a human friendly string representation of an object with computed properties.
Parameters: names – Each positional argument gives the name of a property to include in the rendered object representation. Returns: The rendered object representation (a string). This method generates a user friendly textual representation for objects that use computed properties created using the
property_managermodule.
-
__eq__(other)[source]¶ Enable equality comparison and hashing for
PropertyManagersubclasses.
-
__ne__(other)[source]¶ Enable non-equality comparison for
PropertyManagersubclasses.
-
__lt__(other)[source]¶ Enable “less than” comparison for
PropertyManagersubclasses.
-
__le__(other)[source]¶ Enable “less than or equal” comparison for
PropertyManagersubclasses.
-
__gt__(other)[source]¶ Enable “greater than” comparison for
PropertyManagersubclasses.
-
__ge__(other)[source]¶ Enable “greater than or equal” comparison for
PropertyManagersubclasses.
-
__hash__()[source]¶ Enable hashing for
PropertyManagersubclasses.This method makes it possible to add
PropertyManagerobjects to sets and use them as dictionary keys. The hashes computed by this method are based on the values inkey_values.
-
__repr__()[source]¶ Render a human friendly string representation of an object with computed properties.
Returns: The rendered object representation (a string). This method uses
render_properties()to render the properties whose names are given byrepr_properties. When the object doesn’t have any key properties,__repr__()assumes that all of the object’s properties are idempotent and may be evaluated at any given time without worrying too much about performance (refer to thereproption for an escape hatch).
-
-
class
property_manager.custom_property(*args, **kw)[source]¶ Custom
propertysubclass that supports additional features.The
custom_propertyclass implements Python’s descriptor protocol to provide a decorator that turns methods into computed properties with several additional features.The additional features are controlled by attributes defined on the
custom_propertyclass. These attributes (documented below) are intended to be changed by the constructor (__new__()) and/or classes that inherit fromcustom_property.-
cached= False¶ If this attribute is set to
Truethe property’s value is computed only once and then cached in an object’s__dict__. The next time you access the attribute’s value the cached value is automatically returned. By combining thecachedandresettableoptions you get a cached property whose cached value can be cleared. If the value should never be recomputed then don’t enable theresettableoption.See also: cached_propertyandlazy_property.
-
dynamic= False¶ Truewhen thecustom_propertysubclass was dynamically constructed by__new__(),Falseotherwise. Used bycompose_usage_notes()to decide whether to link to the documentation of the subclass or not (because it’s impossible to link to anonymous classes).
-
environment_variable= None¶ If this attribute is set to the name of an environment variable the property’s value will default to the value of the environment variable. If the environment variable isn’t set the property falls back to its computed value.
-
key= False¶ If this attribute is
Truethe property’s name is included in the value ofkey_propertieswhich means that the property’s value becomes part of the “key” that is used to compare, sort and hashPropertyManagerobjects. There are a few things to be aware of with regards to key properties and their values:- The property’s value must be set during object initialization (the same
as for
requiredproperties) and it cannot be changed after it is initially assigned a value (because allowing this would “compromise” the results of the__hash__()method). - The property’s value must be hashable (otherwise it can’t be used by the
__hash__()method).
See also: key_property.- The property’s value must be set during object initialization (the same
as for
-
repr= True¶ By default
PropertyManager.__repr__()includes the names and values of all properties that aren’tNoneinrepr()output. If you want to omit a certain property you can setreprtoFalse.Examples of why you would want to do this include property values that contain secrets or are expensive to calculate and data structures with cycles which cause
repr()to die a slow and horrible death :-).
-
required= False¶ If this attribute is set to
Truethe property requires a value to be set during the initialization of the object that owns the property. For this to work the class that owns the property needs to inherit fromPropertyManager.See also: required_property.The constructor of
PropertyManagerwill ensure that required properties are set to values that aren’tNone. Required properties must be set by providing keyword arguments to the constructor of the class that inherits fromPropertyManager. WhenPropertyManager.__init__()notices that required properties haven’t been set it raises aTypeErrorsimilar to the type error raised by Python when required arguments are missing in a function call. Here’s an example:from property_manager import PropertyManager, required_property, mutable_property class Example(PropertyManager): @required_property def important(self): "A very important attribute." @mutable_property def optional(self): "A not so important attribute." return 13
Let’s construct an instance of the class defined above:
>>> Example() Traceback (most recent call last): File "property_manager/__init__.py", line 107, in __init__ raise TypeError("%s (%s)" % (msg, concatenate(missing_properties))) TypeError: missing 1 required argument ('important')
As expected it complains that a required property hasn’t been initialized. Here’s how it’s supposed to work:
>>> Example(important=42) Example(important=42, optional=13)
-
resettable= False¶ If this attribute is set to
Truethe property can be reset to its default or computed value usingdelanddelattr(). This works by removing the assigned or cached value from the object’s__dict__.See also: mutable_propertyandcached_property.
-
usage_notes= True¶ If this attribute is
Trueinject_usage_notes()is used to inject usage notes into the documentation of the property. You can set this attribute toFalseto disableinject_usage_notes().
-
writable= False¶ If this attribute is set to
Truethe property supports assignment. The assigned value is stored in the__dict__of the object that owns the property.See also: writable_property,mutable_propertyandrequired_property.A relevant note about how Python looks up attributes: When an attribute is looked up and exists in an object’s
__dict__Python ignores any property (descriptor) by the same name and immediately returns the value that was found in the object’s__dict__.
-
static
__new__(cls, *args, **options)[source]¶ Constructor for
custom_propertysubclasses and instances.To construct a subclass:
Parameters: - args – The first positional argument is used as the name of the subclass (defaults to ‘customized_property’).
- options – Each keyword argument gives the name of an option
(
writable,resettable,cached,required,environment_variable,repr) and the value to use for that option (True,Falseor a string).
Returns: A dynamically constructed subclass of
custom_propertywith the given options.To construct an instance:
Parameters: args – The first positional argument is the function that’s called to compute the value of the property. Returns: A custom_propertyinstance corresponding to the class whose constructor was called.Here’s an example of how the subclass constructor can be used to dynamically construct custom properties with specific options:
from property_manager import custom_property class WritableCachedPropertyDemo(object): @custom_property(cached=True, writable=True) def customized_test_property(self): return 42
The example above defines and uses a property whose computed value is cached and which supports assignment of new values. The example could have been made even simpler:
from property_manager import cached_property class WritableCachedPropertyDemo(object): @cached_property(writable=True) def customized_test_property(self): return 42
Basically you can take any of the custom property classes defined in the
property_managermodule and call the class with keyword arguments corresponding to the options you’d like to change.
-
__init__(*args, **kw)[source]¶ Initialize a
custom_propertyobject.Parameters: Automatically calls
inject_usage_notes()during initialization (only ifUSAGE_NOTES_ENABLEDisTrue).
-
ensure_callable(role)[source]¶ Ensure that a decorated value is in fact callable.
Parameters: role – The value’s role (one of ‘fget’, ‘fset’ or ‘fdel’). Raises: exceptions.ValueErrorwhen the value isn’t callable.
-
inject_usage_notes()[source]¶ Inject the property’s semantics into its documentation.
Calls
compose_usage_notes()to get a description of the property’s semantics and appends this to the property’s documentation. If the property doesn’t have documentation it will not be added.
-
compose_usage_notes()[source]¶ Get a description of the property’s semantics to include in its documentation.
Returns: A list of strings describing the semantics of the custom_propertyin reStructuredText format with Sphinx directives.
-
__get__(obj, type=None)[source]¶ Get the assigned, cached or computed value of the property.
Parameters: - obj – The instance that owns the property.
- type – The class that owns the property.
Returns: The value of the property.
-
__set__(obj, value)[source]¶ Override the computed value of the property.
Parameters: - obj – The instance that owns the property.
- value – The new value for the property.
Raises: AttributeErrorifwritableisFalse.
-
__delete__(obj)[source]¶ Reset the assigned or cached value of the property.
Parameters: obj – The instance that owns the property. Raises: AttributeErrorifresettableisFalse.Once the property has been deleted the next read will evaluate the decorated function to compute the value.
-
-
class
property_manager.writable_property(*args, **kw)[source]¶ A computed property that supports assignment.
This is a variant of
custom_propertythat has thewritableoption enabled by default.
-
class
property_manager.required_property(*args, **kw)[source]¶ A property that requires a value to be set.
This is a variant of
writable_propertythat has therequiredoption enabled by default. Refer to the documentation of therequiredoption for an example.
-
class
property_manager.key_property(*args, **kw)[source]¶ A property whose value is used for comparison and hashing.
This is a variant of
custom_propertythat has thekeyandrequiredoptions enabled by default.
-
class
property_manager.mutable_property(*args, **kw)[source]¶ A computed property that can be assigned and reset.
This is a variant of
writable_propertythat has theresettableoption enabled by default.
-
class
property_manager.lazy_property(*args, **kw)[source]¶ A computed property whose value is computed once and cached.
This is a variant of
custom_propertythat has thecachedoption enabled by default.
-
class
property_manager.cached_property(*args, **kw)[source]¶ A computed property whose value is computed once and cached, but can be reset.
This is a variant of
lazy_propertythat has theresettableoption enabled by default.
property_manager.sphinx¶
Integration with the Sphinx documentation generator.
The property_manager.sphinx module uses the Sphinx extension API to
customize the process of generating Sphinx based Python documentation. It
modifies the documentation of PropertyManager subclasses to include
an overview of superclasses, properties, public methods and special methods. It
also includes hints about required properties and how the values of properties
can be set by passing keyword arguments to the class initializer.
For a simple example check out the documentation of the TypeInspector
class. Yes, that means this module is being used to document itself :-).
The entry point to this module is the setup() function.
-
property_manager.sphinx.setup(app)[source]¶ Make it possible to use
property_manager.sphinxas a Sphinx extension.Parameters: app – The Sphinx application object. To enable the use of this module you add the name of the module to the
extensionsoption in yourdocs/conf.pyscript:extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'property_manager.sphinx', ]
When Sphinx sees the
property_manager.sphinxname it will import this module and call thesetup()function which will connect theappend_property_docs()function toautodoc-process-docstringevents.
-
property_manager.sphinx.append_property_docs(app, what, name, obj, options, lines)[source]¶ Render an overview with properties and methods of
PropertyManagersubclasses.This function implements a callback for
autodoc-process-docstringthat generates and appends an overview of member details to the docstrings ofPropertyManagersubclasses.The parameters expected by this function are those defined for Sphinx event callback functions (i.e. I’m not going to document them here :-).
-
class
property_manager.sphinx.TypeInspector(**kw)[source]¶ Introspection of
PropertyManagersubclasses.Here’s an overview of the
TypeInspectorclass:Superclass: PropertyManagerPublic methods: format_methods()andformat_properties()Properties: custom_properties,initializer_hint,members,methods,overview,properties,public_methods,required_hint,special_methodsandtypeWhen you initialize a
TypeInspectorobject you are required to provide a value for thetypeproperty. You can set the value of thetypeproperty by passing a keyword argument to the class initializer.-
custom_properties[source]¶ A list of tuples with the names and values of custom properties.
Note
The
custom_propertiesproperty is alazy_property. This property’s value is computed once (the first time it is accessed) and the result is cached.
-
initializer_hint[source]¶ A hint that properties can be set using keyword arguments to the initializer (a string or
None).Note
The
initializer_hintproperty is alazy_property. This property’s value is computed once (the first time it is accessed) and the result is cached.
-
members[source]¶ An iterable of tuples with the names and values of the non-inherited members of
type.Note
The
membersproperty is alazy_property. This property’s value is computed once (the first time it is accessed) and the result is cached.
-
methods[source]¶ An iterable of method names of
type.Note
The
methodsproperty is alazy_property. This property’s value is computed once (the first time it is accessed) and the result is cached.
-
overview[source]¶ Render an overview with related members grouped together.
Note
The
overviewproperty is alazy_property. This property’s value is computed once (the first time it is accessed) and the result is cached.
-
properties[source]¶ An iterable of tuples with property names (strings) and values (
propertyobjects).Note
The
propertiesproperty is alazy_property. This property’s value is computed once (the first time it is accessed) and the result is cached.
-
public_methods[source]¶ An iterable of strings with the names of public methods (that don’t start with an underscore).
Note
The
public_methodsproperty is alazy_property. This property’s value is computed once (the first time it is accessed) and the result is cached.
-
required_hint[source]¶ A hint about required properties (a string or
None).Note
The
required_hintproperty is alazy_property. This property’s value is computed once (the first time it is accessed) and the result is cached.
-
special_methods[source]¶ An iterable of strings with the names of special methods (surrounded in double underscores).
Note
The
special_methodsproperty is alazy_property. This property’s value is computed once (the first time it is accessed) and the result is cached.
-
type[source]¶ A subclass of
PropertyManager.Note
The
typeproperty is arequired_property. You are required to provide a value for this property by calling the constructor of the class that defines the property with a keyword argument named type (unless a custom constructor is defined, in this case please refer to the documentation of that constructor). You can change the value of this property using normal attribute assignment syntax.
-