SQLAlchemy 0.5 Documentation

Multiple Pages | One Page
Version: 0.5.0rc1 Last Updated: 09/11/08 17:04:35

module sqlalchemy.orm.collections

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 InstrumentedCollectionAttribute 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(object):
    # ...

    @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 relation(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 InstrumentedCollectionAttribute are also reachable through the adapter, allowing for some very sophisticated behavior.

Module Functions

def attribute_mapped_collection(attr_name)

A dictionary-based collection type with attribute-based keying.

Returns a MappedCollection factory with a keying based on the 'attr_name' attribute of entities in the collection.

The key value must be immutable for the lifetime of the object. You can not, for example, map on foreign key values if those key values will change during the session, i.e. from None to a database-assigned integer after a session flush.

def collection_adapter(collection)

Fetch the CollectionAdapter for a collection.

def column_mapped_collection(mapping_spec)

A dictionary-based collection type with column-based keying.

Returns a MappedCollection factory with a keying function generated from mapping_spec, which may be a Column or a sequence of Columns.

The key value must be immutable for the lifetime of the object. You can not, for example, map on foreign key values if those key values will change during the session, i.e. from None to a database-assigned integer after a session flush.

def mapped_collection(keyfunc)

A dictionary-based collection type with arbitrary keying.

Returns a MappedCollection factory with a keying function generated from keyfunc, a callable that takes an entity and returns a key value.

The key value must be immutable for the lifetime of the object. You can not, for example, map on foreign key values if those key values will change during the session, i.e. from None to a database-assigned integer after a session flush.

class collection(object)

Decorators for entity collection classes.

The decorators fall into two groups: annotations and interception recipes.

The annotating decorators (appender, remover, iterator, internally_instrumented, on_link) indicate the method's purpose and take no arguments. They are not written with parens:

@collection.appender
def append(self, append): ...

The recipe decorators all require parens, even those that take no arguments:

@collection.adds('entity'):
def insert(self, position, entity): ...

@collection.removes_return()
def popitem(self): ...

Decorators can be specified in long-hand for Python 2.3, or with the class-level dict attribute '__instrumentation__'- see the source for details.

back to section top

class MappedCollection(dict)

A basic dictionary-based collection class.

Extends dict with the minimal bag semantics that collection classes require. set and remove are implemented in terms of a keying function: any callable that takes an object and returns an object for use as a dictionary key.

def __init__(self, keyfunc)

Create a new collection with keying provided by keyfunc.

keyfunc may be any callable any callable that takes an object and returns an object for use as a dictionary key.

The keyfunc will be called every time the ORM needs to add a member by value-only (such as when loading instances from the database) or remove a member. The usual cautions about dictionary keying apply- keyfunc(object) should return the same output for the life of the collection. Keying based on mutable properties can result in unreachable instances "lost" in the collection.

def remove(self, value, _sa_initiator=None)

Remove an item by value, consulting the keyfunc for the key.

def set(self, value, _sa_initiator=None)

Add an item by value, consulting the keyfunc for the key.

back to section top

class CollectionAdapter(object)

Bridges between the ORM and arbitrary Python collections.

Proxies base-level collection operations (append, remove, iterate) to the underlying Python collection, and emits add/remove events for entities entering or leaving the collection.

The ORM uses an CollectionAdapter exclusively for interaction with entity collections.

def __init__(self, attr, owner_state, data)

Construct a new CollectionAdapter.

def adapt_like_to_iterable(self, obj)

Converts collection-compatible objects to an iterable of values.

Can be passed any type of object, and if the underlying collection determines that it can be adapted into a stream of values it can use, returns an iterable of values suitable for append()ing.

This method may raise TypeError or any other suitable exception if adaptation fails.

If a converter implementation is not supplied on the collection, a default duck-typing-based implementation is used.

def append_with_event(self, item, initiator=None)

Add an entity to the collection, firing mutation events.

def append_without_event(self, item)

Add or restore an entity to the collection, firing no events.

def clear_with_event(self, initiator=None)

Empty the collection, firing a mutation event for each entity.

def clear_without_event(self)

Empty the collection, firing no events.

data = property()

The entity collection being adapted.

def fire_append_event(self, item, initiator=None)

Notify that a entity has entered the collection.

Initiator is the InstrumentedAttribute that initiated the membership mutation, and should be left as None unless you are passing along an initiator value from a chained operation.

def fire_pre_remove_event(self, initiator=None)

Notify that an entity is about to be removed from the collection.

Only called if the entity cannot be removed after calling fire_remove_event().

def fire_remove_event(self, item, initiator=None)

Notify that a entity has been removed from the collection.

Initiator is the InstrumentedAttribute that initiated the membership mutation, and should be left as None unless you are passing along an initiator value from a chained operation.

def link_to_self(self, data)

Link a collection to this adapter, and fire a link event.

def remove_with_event(self, item, initiator=None)

Remove an entity from the collection, firing mutation events.

def remove_without_event(self, item)

Remove an entity from the collection, firing no events.

def unlink(self, data)

Unlink a collection from any adapter, and fire a link event.

def __iter__(self)

Iterate over entities in the collection.

def __len__(self)

Count entities in the collection.

def __nonzero__(self)
back to section top
Up: API Documentation | Previous: module sqlalchemy.orm.attributes | Next: module sqlalchemy.orm.interfaces