SQLAlchemy 0.5 Documentation - module sqlalchemy.orm.attributes

# SQLAlchemy 0.5 Documentation

Multiple Pages | One Page
Version: 0.5.0rc3 Last Updated: 11/07/08 13:55:35

### module sqlalchemy.orm.attributes

Defines SQLAlchemy's system of class instrumentation..

This module is usually not directly visible to user applications, but defines a large part of the ORM's interactivity.

SQLA's instrumentation system is completely customizable, in which case an understanding of the general mechanics of this module is helpful. An example of full customization is in /examples/custom_attributes.

### Module Functions

def collect_management_factories_for(cls)

Return a collection of factories in play or specified for a hierarchy.

Traverses the entire inheritance graph of a cls and returns a collection of instrumentation factories for those classes. Factories are extracted from active ClassManagers, if available, otherwise instrumentation_finders is consulted.

def del_attribute(instance, key)
def find_native_user_instrumentation_hook(cls)

Find user-specified instrumentation management for a class.

def get_attribute(instance, key)
def get_history(state, key, **kwargs)
def has_parent(cls, obj, key, optimistic=False)

TODO

def identity_equal(a, b)
def init_collection(state, key)

Initialize a collection attribute and return the collection adapter.

def is_instrumented(instance, key)
def proxied_attribute_factory(descriptor)

Create an InstrumentedAttribute / user descriptor hybrid.

Returns a new InstrumentedAttribute type that delegates descriptor behavior and getattr() to the given descriptor.

def register_attribute(class_, key, uselist, useobject, callable_=None, proxy_property=None, mutable_scalars=False, impl_class=None, **kwargs)
def register_class(class_)

TODO

def set_attribute(instance, key, value)
def unregister_attribute(class_, key)
def unregister_class(class_)

TODO

### class AttributeImpl(object)

internal implementation for instrumented attributes.

def __init__(self, class_, key, callable_, class_manager, trackparent=False, extension=None, compare_function=None, active_history=False, **kwargs)

Construct an AttributeImpl.

class_
  the class to be instrumented.
key
  string name of the attribute
callable_
  optional function which generates a callable based on a parent instance, which produces the "default" values for a scalar or collection attribute when it's first accessed, if not present already.
trackparent
  if True, attempt to track if an instance has a parent attached to it via this attribute.
extension
  a single or list of AttributeExtension object(s) which will receive set/delete/append/remove/etc. events.
compare_function
  a function that compares two values which are normally assignable to this attribute.
active_history
  indicates that get_history() should always return the "old" value, even if it means executing a lazy callable upon attribute change. This flag is set to True if any extensions are present.

def append(self, state, value, initiator, passive=False)
def get(self, state, passive=False)

Retrieve a value from the given object.

If a callable is assembled on this object's attribute, and passive is False, the callable will be executed and the resulting value will be set as the new value for this attribute.

def get_committed_value(self, state, passive=False)

return the unchanged value of this attribute

def get_history(self, state, passive=False)
def hasparent(self, state, optimistic=False)

Return the boolean value of a hasparent flag attached to the given item.

The optimistic flag determines what the default return value should be if no hasparent flag can be located.

As this function is used to determine if an instance is an orphan, instances that were loaded from storage should be assumed to not be orphans, until a True/False value for this flag is set.

An instance attribute that is loaded by a callable function will also not have a hasparent flag.

def initialize(self, state)

Initialize this attribute on the given object instance with an empty value.

def remove(self, state, value, initiator, passive=False)
def set(self, state, value, initiator)
def set_callable(self, state, callable_)

Set a callable function for this attribute on the given object.

This callable will be executed when the attribute is next accessed, and is assumed to construct part of the instances previously stored state. When its value or values are loaded, they will be established as part of the instance's committed state. While trackparent information will be assembled for these instances, attribute-level event handlers will not be fired.

The callable overrides the class level callable set in the `InstrumentedAttribute` constructor.

def set_committed_value(self, state, value)

set an attribute value on the given instance and 'commit' it.

def sethasparent(self, state, value)

Set a boolean flag on the given item corresponding to whether or not it is attached to a parent object via the attribute represented by this `InstrumentedAttribute`.

back to section top

### class ClassManager(dict)

tracks state information at the class level.

def __init__(self, class_)

Construct a new `ClassManager`.

attributes = property()
def deferred_scalar_loader(cls, state, keys)

TODO

def dispose(self)

Dissasociate this instance from its class.

def get_impl(self, key)
def has_parent(self, state, key, optimistic=False)

TODO

def has_state(self, instance)

True if an InstanceState is installed on the instance.

def initialize_collection(self, key, state, factory)
def install_descriptor(self, key, inst)
def install_member(self, key, implementation)
def install_state(self, instance, state)
instantiable = property()
def instrument_attribute(self, key, inst, propagated=False)
def instrument_collection_class(self, key, collection_class)
def is_instrumented(self, key, search=False)
def manage(self)

Mark this instance as the manager for its class.

def manager_getter(self)
def new_instance(self, state=None)
def setup_instance(self, instance, with_state=None)

Register an InstanceState with an instance.

def state_getter(self)

Return a (instance) -> InstanceState callable.

"state getter" callables should raise either KeyError or AttributeError if no InstanceState could be found for the instance.

def state_of(self, instance)

Retrieve the InstanceState of an instance.

May raise KeyError or AttributeError if no state is available.

def uninstall_descriptor(self, key)
def uninstall_member(self, key)
def uninstrument_attribute(self, key, propagated=False)
def unregister(self)
def __nonzero__(self)

All ClassManagers are non-zero regardless of attribute state.

back to section top

### class CollectionAttributeImpl(AttributeImpl)

A collection-holding attribute that instruments changes in membership.

Only handles collections of instrumented objects.

InstrumentedCollectionAttribute holds an arbitrary, user-specified container object (defaulting to a list) and brokers access to the CollectionAdapter, a "view" onto that object that presents consistent bag semantics to the orm layer independent of the user data implementation.

def __init__(self, class_, key, callable_, class_manager, typecallable=None, trackparent=False, extension=None, copy_function=None, compare_function=None, **kwargs)

Construct a new `CollectionAttributeImpl`.

def append(self, state, value, initiator, passive=False)
def delete(self, state)
def fire_append_event(self, state, value, initiator)
def fire_pre_remove_event(self, state, initiator)
def fire_remove_event(self, state, value, initiator)
def get_collection(self, state, user_data=None, passive=False)

Retrieve the CollectionAdapter associated with the given state.

Creates a new CollectionAdapter if one does not exist.

def get_history(self, state, passive=False)
def initialize(self, state)

Initialize this attribute with an empty collection.

def remove(self, state, value, initiator, passive=False)
def set(self, state, value, initiator)

Set a value on the given object.

initiator is the `InstrumentedAttribute` that initiated the `set()` operation and is used to control the depth of a circular setter operation.

def set_committed_value(self, state, value)

Set an attribute value on the given instance and 'commit' it.

back to section top

### class Events(object)

def __init__(self)

Construct a new `Events`.

def add_listener(self, event, listener)
def remove_listener(self, event, listener)
def run(self, event, *args, **kwargs)
back to section top

### class GenericBackrefExtension(AttributeExtension)

An extension which synchronizes a two-way relationship.

A typical two-way relationship is a parent object containing a list of child objects, where each child object references the parent. The other are two objects which contain scalar references to each other.

def __init__(self, key)

Construct a new `GenericBackrefExtension`.

def append(self, state, child, initiator)
def remove(self, state, child, initiator)
def set(self, state, child, oldchild, initiator)
back to section top

### class History(tuple)

A 3-tuple of added, unchanged and deleted values.

Each tuple member is an iterable sequence.

added = property()

itemgetter(item, ...) --> itemgetter object

Return a callable object that fetches the given item(s) from its operand. After, f=itemgetter(2), the call f(r) returns r[2]. After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])

def as_state(self)
deleted = property()

itemgetter(item, ...) --> itemgetter object

Return a callable object that fetches the given item(s) from its operand. After, f=itemgetter(2), the call f(r) returns r[2]. After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])

def from_attribute(cls, attribute, state, current)
def has_changes(self)
def non_added(self)
def non_deleted(self)
def sum(self)
unchanged = property()

itemgetter(item, ...) --> itemgetter object

Return a callable object that fetches the given item(s) from its operand. After, f=itemgetter(2), the call f(r) returns r[2]. After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])

def __nonzero__(self)
back to section top

### class InstanceState(object)

tracks state information at the instance level.

def __init__(self, obj, manager)

Construct a new `InstanceState`.

def check_modified(self)
def commit(self, keys)

Commit attributes.

This is used by a partial-attribute load operation to mark committed those attributes which were refreshed from the database.

Attributes marked as "expired" can potentially remain "expired" after this step if a value was not populated in state.dict.

def commit_all(self)

commit all attributes unconditionally.

This is used after a flush() or a full load/refresh to remove all pending state from the instance.

> - all attributes are marked as "committed"
> - the "strong dirty reference" is removed
> - the "modified" flag is set to False
> - any "expired" markers/callables are removed.

Attributes marked as "expired" can potentially remain "expired" after this step if a value was not populated in state.dict.

def detach(self)
def dispose(self)
def expire_attributes(self, attribute_names)
def get_history(self, key, **kwargs)
def get_impl(self, key)
def get_inst(self, key)
def get_pending(self, key)
def initialize(self, key)
def initialize_instance(*mixed, **kwargs)
def modified_event(self, attr, should_copy, previous, passive=False)
def obj(self)
def reset(self, key)

remove the given attribute and any callables associated with it.

def set_callable(self, key, callable_)
sort_key = property()
unmodified = property()

a set of keys which have no uncommitted changes

unloaded = property()

a set of keys which do not have a loaded value.

This includes expired attributes and any other attribute that was never populated or modified.

def value_as_iterable(self, key, passive=False)

return an InstanceState attribute as a list, regardless of it being a scalar or collection-based attribute.

returns None if passive is not PASSIVE_OFF and the getter returns PASSIVE_NORESULT.

def __call__(self)

__call__ allows the InstanceState to act as a deferred callable for loading expired attributes, which is also serializable.

back to section top

### class InstrumentationRegistry(object)

Private instrumentation registration singleton.

def create_manager_for_cls(self, class_)
def manager_of_class(self, cls)
def state_of(self, instance)
def state_or_default(self, instance, default=None)
def unregister(self, class_)
back to section top

### class InstrumentedAttribute(QueryableAttribute)

Public-facing descriptor, placed in the mapped class dictionary.

def __delete__(self, instance)
def __get__(self, instance, owner)
def __set__(self, instance, value)
back to section top

### class MutableScalarAttributeImpl(ScalarAttributeImpl)

represents a scalar value-holding InstrumentedAttribute, which can detect changes within the value itself.

def __init__(self, class_, key, callable_, class_manager, copy_function=None, compare_function=None, **kwargs)

Construct a new `MutableScalarAttributeImpl`.

def check_mutable_modified(self, state)
def commit_to_state(self, state, dest)
def get_history(self, state, passive=False)
def set(self, state, value, initiator)
back to section top

### class PendingCollection(object)

A writable placeholder for an unloaded collection.

Stores items appended to and removed from a collection that has not yet been loaded. When the collection is loaded, the changes stored in PendingCollection are applied to it to produce the final result.

def __init__(self)

Construct a new `PendingCollection`.

def append(self, value)
def remove(self, value)
back to section top

### class QueryableAttribute(PropComparator)

def __init__(self, impl, comparator=None, parententity=None)

Construct an InstrumentedAttribute.

comparator
  a sql.Comparator to which class-level compare/math events will be sent

def get_history(self, instance, **kwargs)
def hasparent(self, state, optimistic=False)
def label(self, name)
def operate(self, op, *other, **kwargs)
def reverse_operate(self, op, other, **kwargs)
def __clause_element__(self)
def __selectable__(self)
back to section top

### class ScalarAttributeImpl(AttributeImpl)

represents a scalar value-holding InstrumentedAttribute.

def delete(self, state)
def fire_remove_event(self, state, value, initiator)
def fire_replace_event(self, state, value, previous, initiator)
def get_history(self, state, passive=False)
def set(self, state, value, initiator)
type = property()
back to section top

### class ScalarObjectAttributeImpl(ScalarAttributeImpl)

represents a scalar-holding InstrumentedAttribute, where the target object is also instrumented.

Adds events to delete/set operations.

def __init__(self, class_, key, callable_, class_manager, trackparent=False, extension=None, copy_function=None, compare_function=None, **kwargs)

Construct a new `ScalarObjectAttributeImpl`.

def delete(self, state)
def fire_remove_event(self, state, value, initiator)
def fire_replace_event(self, state, value, previous, initiator)
def get_history(self, state, passive=False)
def set(self, state, value, initiator)

Set a value on the given InstanceState.

initiator is the `InstrumentedAttribute` that initiated the `set()` operation and is used to control the depth of a circular setter operation.

back to section top

### class attrgetter(object)

attrgetter(attr, ...) --> attrgetter object

Return a callable object that fetches the given attribute(s) from its operand. After, f=attrgetter('name'), the call f(r) returns r.name. After, g=attrgetter('name', 'date'), the call g(r) returns (r.name, r.date).

back to section top

### class itemgetter(object)

itemgetter(item, ...) --> itemgetter object

Return a callable object that fetches the given item(s) from its operand. After, f=itemgetter(2), the call f(r) returns r[2]. After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])

back to section top