module documentation

Support for collections of mapped entities. The collections package supplies the machinery used to inform the ORM of collection membership changes. An instrumentation via decoration approach is used, allowing arbitrary types (including built-ins) to be used as entity collections without requiring inheritance from a base class. Instrumentation decoration relays membership change events to the :class:`.CollectionAttributeImpl` that is currently managing the collection. The decorators observe function call arguments and return values, tracking entities entering or leaving the collection. Two decorator approaches are provided. One is a bundle of generic decorators that map function arguments and return values to events:: from sqlalchemy.orm.collections import collection class MyClass: # ... @collection.adds(1) def store(self, item): self.data.append(item) @collection.removes_return() def pop(self): return self.data.pop() The second approach is a bundle of targeted decorators that wrap appropriate append and remove notifiers around the mutation methods present in the standard Python ``list``, ``set`` and ``dict`` interfaces. These could be specified in terms of generic decorator recipes, but are instead hand-tooled for increased efficiency. The targeted decorators occasionally implement adapter-like behavior, such as mapping bulk-set methods (``extend``, ``update``, ``__setslice__``, etc.) into the series of atomic mutation events that the ORM requires. The targeted decorators are used internally for automatic instrumentation of entity collection classes. Every collection class goes through a transformation process roughly like so: 1. If the class is a built-in, substitute a trivial sub-class 2. Is this class already instrumented? 3. Add in generic decorators 4. Sniff out the collection interface through duck-typing 5. Add targeted decoration to any undecorated interface method This process modifies the class at runtime, decorating methods and adding some bookkeeping properties. This isn't possible (or desirable) for built-in classes like ``list``, so trivial sub-classes are substituted to hold decoration:: class InstrumentedList(list): pass Collection classes can be specified in ``relationship(collection_class=)`` as types or a function that returns an instance. Collection classes are inspected and instrumented during the mapper compilation phase. The collection_class callable will be executed once to produce a specimen instance, and the type of that specimen will be instrumented. Functions that return built-in types like ``lists`` will be adapted to produce instrumented instances. When extending a known type like ``list``, additional decorations are not generally not needed. Odds are, the extension method will delegate to a method that's already instrumented. For example:: class QueueIsh(list): def push(self, item): self.append(item) def shift(self): return self.pop(0) There's no need to decorate these methods. ``append`` and ``pop`` are already instrumented as part of the ``list`` interface. Decorating them would fire duplicate events, which should be avoided. The targeted decoration tries not to rely on other methods in the underlying collection class, but some are unavoidable. Many depend on 'read' methods being present to properly instrument a 'write', for example, ``__setitem__`` needs ``__getitem__``. "Bulk" methods like ``update`` and ``extend`` may also reimplemented in terms of atomic appends and removes, so the ``extend`` decoration will actually perform many ``append`` operations and not call the underlying method at all. Tight control over bulk operation and the firing of events is also possible by implementing the instrumentation internally in your methods. The basic instrumentation package works under the general assumption that collection mutation will not raise unusual exceptions. If you want to closely orchestrate append and remove events with exception management, internal instrumentation may be the answer. Within your method, ``collection_adapter(self)`` will retrieve an object that you can use for explicit control over triggering append and remove events. The owning object and :class:`.CollectionAttributeImpl` are also reachable through the adapter, allowing for some very sophisticated behavior.

Class collection Decorators for entity collection classes.
Class CollectionAdapter Bridges between the ORM and arbitrary Python collections.
Class InstrumentedDict An instrumented version of the built-in dict.
Class InstrumentedList An instrumented version of the built-in list.
Class InstrumentedSet An instrumented version of the built-in set.
Class KeyFuncDict Base for ORM mapped dictionary classes.
Function attribute_keyed_dict A dictionary-based collection type with attribute-based keying.
Function bulk_replace Load a new collection, firing events based on prior like membership.
Function collection_adapter Fetch the :class:`.CollectionAdapter` for a collection.
Function column_keyed_dict A dictionary-based collection type with column-based keying.
Function keyfunc_mapping A dictionary-based collection type with arbitrary keying.
Function prepare_instrumentation Prepare a callable for future use as a collection class factory.
Class _AdaptedCollectionProtocol Undocumented
Class _CollectionConverterProtocol Undocumented
Function __before_pop An event which occurs on a before a pop() operation occurs.
Function __del Run del events.
Function __go Undocumented
Function __set Run set events.
Function __set_wo_mutation Run set wo mutation events.
Function _assert_required_roles ensure all roles are present, and apply implicit instrumentation if needed
Function _dict_decorators Tailored instrumentation wrappers for any dict-like mapping class.
Function _instrument_class Modify methods in a class and install instrumentation.
Function _instrument_membership_mutator Route method args and/or return value through the collection adapter.
Function _list_decorators Tailored instrumentation wrappers for any list-like class.
Function _locate_roles_and_methods search for _sa_instrument_role-decorated methods in method resolution order, assign to roles.
Function _set_binops_check_loose Allow anything set-like to participate in set binops.
Function _set_binops_check_strict Allow only set, frozenset and self.__class__-derived objects in binops.
Function _set_collection_attributes apply ad-hoc instrumentation from decorators, class-level defaults and implicit role declarations
Function _set_decorators Tailored instrumentation wrappers for any set-like class.
Function _setup_canned_roles see if this class has "canned" roles based on a known collection type (dict, set, list). Apply those roles as needed to the "roles" dictionary, and also prepare "decorator" methods
Type Variable _COL Undocumented
Type Variable _FN Undocumented
Type Variable _KT Undocumented
Type Variable _T Undocumented
Type Variable _VT Undocumented
Type Alias _CollectionFactoryType Undocumented
Variable __canned_instrumentation Undocumented
Variable __instrumentation_mutex Undocumented
Variable __interfaces Undocumented
Variable _set_binop_bases Undocumented
def attribute_keyed_dict(attr_name: str, *, ignore_unpopulated_attribute: bool = False) -> Type[KeyFuncDict[_KT, _KT]]: (source)

A dictionary-based collection type with attribute-based keying. .. versionchanged:: 2.0 Renamed :data:`.attribute_mapped_collection` to :func:`.attribute_keyed_dict`. Returns a :class:`.KeyFuncDict` factory which will produce new dictionary keys based on the value of a particular named attribute on ORM mapped instances to be added to the dictionary. .. note:: the value of the target attribute must be assigned with its value at the time that the object is being added to the dictionary collection. Additionally, changes to the key attribute are **not tracked**, which means the key in the dictionary is not automatically synchronized with the key value on the target object itself. See :ref:`key_collections_mutations` for further details. .. seealso:: :ref:`orm_dictionary_collection` - background on use :param attr_name: string name of an ORM-mapped attribute on the mapped class, the value of which on a particular instance is to be used as the key for a new dictionary entry for that instance. :param ignore_unpopulated_attribute: if True, and the target attribute on an object is not populated at all, the operation will be silently skipped. By default, an error is raised. .. versionadded:: 2.0 an error is raised by default if the attribute being used for the dictionary key is determined that it was never populated with any value. The :paramref:`_orm.attribute_keyed_dict.ignore_unpopulated_attribute` parameter may be set which will instead indicate that this condition should be ignored, and the append operation silently skipped. This is in contrast to the behavior of the 1.x series which would erroneously populate the value in the dictionary with an arbitrary key value of ``None``.

def bulk_replace(values, existing_adapter, new_adapter, initiator=None): (source)

Load a new collection, firing events based on prior like membership. Appends instances in ``values`` onto the ``new_adapter``. Events will be fired for any instance not present in the ``existing_adapter``. Any instances in ``existing_adapter`` not present in ``values`` will have remove events fired upon them. :param values: An iterable of collection member instances :param existing_adapter: A :class:`.CollectionAdapter` of instances to be replaced :param new_adapter: An empty :class:`.CollectionAdapter` to load with ``values``

def collection_adapter(collection: Collection[Any]) -> CollectionAdapter: (source)

Fetch the :class:`.CollectionAdapter` for a collection.

def column_keyed_dict(mapping_spec: Union[Type[_KT], Callable[[_KT], _VT]], *, ignore_unpopulated_attribute: bool = False) -> Type[KeyFuncDict[_KT, _KT]]: (source)

A dictionary-based collection type with column-based keying. .. versionchanged:: 2.0 Renamed :data:`.column_mapped_collection` to :class:`.column_keyed_dict`. Returns a :class:`.KeyFuncDict` factory which will produce new dictionary keys based on the value of a particular :class:`.Column`-mapped attribute on ORM mapped instances to be added to the dictionary. .. note:: the value of the target attribute must be assigned with its value at the time that the object is being added to the dictionary collection. Additionally, changes to the key attribute are **not tracked**, which means the key in the dictionary is not automatically synchronized with the key value on the target object itself. See :ref:`key_collections_mutations` for further details. .. seealso:: :ref:`orm_dictionary_collection` - background on use :param mapping_spec: a :class:`_schema.Column` object that is expected to be mapped by the target mapper to a particular attribute on the mapped class, the value of which on a particular instance is to be used as the key for a new dictionary entry for that instance. :param ignore_unpopulated_attribute: if True, and the mapped attribute indicated by the given :class:`_schema.Column` target attribute on an object is not populated at all, the operation will be silently skipped. By default, an error is raised. .. versionadded:: 2.0 an error is raised by default if the attribute being used for the dictionary key is determined that it was never populated with any value. The :paramref:`_orm.column_keyed_dict.ignore_unpopulated_attribute` parameter may be set which will instead indicate that this condition should be ignored, and the append operation silently skipped. This is in contrast to the behavior of the 1.x series which would erroneously populate the value in the dictionary with an arbitrary key value of ``None``.

def keyfunc_mapping(keyfunc: _F, *, ignore_unpopulated_attribute: bool = False) -> Type[KeyFuncDict[_KT, Any]]: (source)

A dictionary-based collection type with arbitrary keying. .. versionchanged:: 2.0 Renamed :data:`.mapped_collection` to :func:`.keyfunc_mapping`. Returns a :class:`.KeyFuncDict` factory with a keying function generated from keyfunc, a callable that takes an entity and returns a key value. .. note:: the given keyfunc is called only once at the time that the target object is being added to the collection. Changes to the effective value returned by the function are not tracked. .. seealso:: :ref:`orm_dictionary_collection` - background on use :param keyfunc: a callable that will be passed the ORM-mapped instance which should then generate a new key to use in the dictionary. If the value returned is :attr:`.LoaderCallableStatus.NO_VALUE`, an error is raised. :param ignore_unpopulated_attribute: if True, and the callable returns :attr:`.LoaderCallableStatus.NO_VALUE` for a particular instance, the operation will be silently skipped. By default, an error is raised. .. versionadded:: 2.0 an error is raised by default if the callable being used for the dictionary key returns :attr:`.LoaderCallableStatus.NO_VALUE`, which in an ORM attribute context indicates an attribute that was never populated with any value. The :paramref:`_orm.mapped_collection.ignore_unpopulated_attribute` parameter may be set which will instead indicate that this condition should be ignored, and the append operation silently skipped. This is in contrast to the behavior of the 1.x series which would erroneously populate the value in the dictionary with an arbitrary key value of ``None``.

Prepare a callable for future use as a collection class factory. Given a collection class factory (either a type or no-arg callable), return another factory that will produce compatible instances when called. This function is responsible for converting collection_class=list into the run-time behavior of collection_class=InstrumentedList.

def __before_pop(collection, _sa_initiator=None): (source)

An event which occurs on a before a pop() operation occurs.

def __del(collection, item, _sa_initiator, key): (source)

Run del events. This event occurs before the collection is actually mutated, *except* in the case of a pop operation, in which case it occurs afterwards. For pop operations, the __before_pop hook is called before the operation occurs.

def __go(lcls): (source)

Undocumented

def __set(collection, item, _sa_initiator, key): (source)

Run set events. This event always occurs before the collection is actually mutated.

def __set_wo_mutation(collection, item, _sa_initiator=None): (source)

Run set wo mutation events. The collection is not mutated.

def _assert_required_roles(cls, roles, methods): (source)

ensure all roles are present, and apply implicit instrumentation if needed

def _dict_decorators() -> Dict[str, Callable[[_FN], _FN]]: (source)

Tailored instrumentation wrappers for any dict-like mapping class.

def _instrument_class(cls): (source)

Modify methods in a class and install instrumentation.

def _instrument_membership_mutator(method, before, argument, after): (source)

Route method args and/or return value through the collection adapter.

def _list_decorators() -> Dict[str, Callable[[_FN], _FN]]: (source)

Tailored instrumentation wrappers for any list-like class.

def _locate_roles_and_methods(cls): (source)

search for _sa_instrument_role-decorated methods in method resolution order, assign to roles.

def _set_binops_check_loose(self: Any, obj: Any) -> bool: (source)

Allow anything set-like to participate in set binops.

def _set_binops_check_strict(self: Any, obj: Any) -> bool: (source)

Allow only set, frozenset and self.__class__-derived objects in binops.

def _set_collection_attributes(cls, roles, methods): (source)

apply ad-hoc instrumentation from decorators, class-level defaults and implicit role declarations

def _set_decorators() -> Dict[str, Callable[[_FN], _FN]]: (source)

Tailored instrumentation wrappers for any set-like class.

def _setup_canned_roles(cls, roles, methods): (source)

see if this class has "canned" roles based on a known collection type (dict, set, list). Apply those roles as needed to the "roles" dictionary, and also prepare "decorator" methods

Undocumented

Value
TypeVar('_COL',
        bound='Collection[Any]')

Undocumented

Value
TypeVar('_FN',
        bound='Callable[..., Any]')

Undocumented

Value
TypeVar('_KT',
        bound=Any)

Undocumented

Value
TypeVar('_T',
        bound=Any)

Undocumented

Value
TypeVar('_VT',
        bound=Any)
_CollectionFactoryType = (source)

Undocumented

Value
Callable[[], '_AdaptedCollectionProtocol']
__canned_instrumentation: util.immutabledict[Any, _CollectionFactoryType] = (source)

Undocumented

__instrumentation_mutex = (source)

Undocumented

__interfaces: util.immutabledict[Any, Tuple[Dict[str, str], Dict[str, Callable[..., Any]]]] = (source)

Undocumented

_set_binop_bases = (source)

Undocumented