Commits

diana  committed af08f2d

just a pep8 pass of lib/sqlalchemy/orm/

  • Participants
  • Parent commits d0400a7

Comments (0)

Files changed (10)

File lib/sqlalchemy/orm/__init__.py

     kwargs.setdefault('expire_on_commit', False)
     return Session(bind=bind, **kwargs)
 
+
 def relationship(argument, secondary=None, **kwargs):
     """Provide a relationship of a primary Mapper to a secondary Mapper.
 
 
     Some arguments accepted by :func:`.relationship` optionally accept a
     callable function, which when called produces the desired value.
-    The callable is invoked by the parent :class:`.Mapper` at "mapper initialization"
-    time, which happens only when mappers are first used, and is assumed
-    to be after all mappings have been constructed.  This can be used
-    to resolve order-of-declaration and other dependency issues, such as
+    The callable is invoked by the parent :class:`.Mapper` at "mapper
+    initialization" time, which happens only when mappers are first used, and
+    is assumed to be after all mappings have been constructed.  This can be
+    used to resolve order-of-declaration and other dependency issues, such as
     if ``Child`` is declared below ``Parent`` in the same file::
 
         mapper(Parent, properties={
     These string arguments are converted into callables that evaluate
     the string as Python code, using the Declarative
     class-registry as a namespace.  This allows the lookup of related
-    classes to be automatic via their string name, and removes the need to import
-    related classes at all into the local module space::
+    classes to be automatic via their string name, and removes the need to
+    import related classes at all into the local module space::
 
         from sqlalchemy.ext.declarative import declarative_base
 
     :func:`.relationship` is at :ref:`relationship_config_toplevel`.
 
     :param argument:
-      a mapped class, or actual :class:`.Mapper` instance, representing the target of
-      the relationship.
+      a mapped class, or actual :class:`.Mapper` instance, representing the
+      target of the relationship.
 
       ``argument`` may also be passed as a callable function
       which is evaluated at mapper initialization time, and may be passed as a
 
       There are only two use cases for ``foreign_keys`` - one, when it is not
       convenient for :class:`.Table` metadata to contain its own foreign key
-      metadata (which should be almost never, unless reflecting a large amount of
-      tables from a MySQL MyISAM schema, or a schema that doesn't actually
+      metadata (which should be almost never, unless reflecting a large amount
+      of tables from a MySQL MyISAM schema, or a schema that doesn't actually
       have foreign keys on it). The other is for extremely
       rare and exotic composite foreign key setups where some columns
       should artificially not be considered as foreign.
       case, use an alternative method.
 
     .. versionchanged:: 0.6
-        :func:`relationship` was renamed from its previous name :func:`relation`.
+        :func:`relationship` was renamed from its previous name
+        :func:`relation`.
 
     """
     return RelationshipProperty(argument, secondary=secondary, **kwargs)
 
+
 def relation(*arg, **kw):
     """A synonym for :func:`relationship`."""
 
     return relationship(*arg, **kw)
 
+
 def dynamic_loader(argument, **kw):
     """Construct a dynamically-loading mapper property.
 
     kw['lazy'] = 'dynamic'
     return relationship(argument, **kw)
 
+
 def column_property(*cols, **kw):
     """Provide a column-level property for use with a Mapper.
 
 
     return ColumnProperty(*cols, **kw)
 
+
 def composite(class_, *cols, **kwargs):
     """Return a composite column-based property for use with a Mapper.
 
 
 
 def backref(name, **kwargs):
-    """Create a back reference with explicit keyword arguments, which are the same
-    arguments one can send to :func:`relationship`.
+    """Create a back reference with explicit keyword arguments, which are the
+    same arguments one can send to :func:`relationship`.
 
     Used with the ``backref`` keyword argument to :func:`relationship` in
     place of a string argument, e.g.::
     """
     return (name, kwargs)
 
+
 def deferred(*columns, **kwargs):
     """Return a :class:`.DeferredColumnProperty`, which indicates this
     object attributes should only be loaded from its corresponding
     """
     return ColumnProperty(deferred=True, *columns, **kwargs)
 
+
 def mapper(class_, local_table=None, *args, **params):
     """Return a new :class:`~.Mapper` object.
 
            this mapper inherits from another mapper using single-table
            inheritance.   When using Declarative, this argument is
            automatically passed by the extension, based on what
-           is configured via the ``__table__`` argument or via the :class:`.Table`
-           produced as a result of the ``__tablename__`` and :class:`.Column`
-           arguments present.
+           is configured via the ``__table__`` argument or via the
+           :class:`.Table` produced as a result of the ``__tablename__``
+           and :class:`.Column` arguments present.
 
         :param always_refresh: If True, all query operations for this mapped
            class will overwrite all data within object instances that already
           See :ref:`include_exclude_cols` for an example.
 
         :param extension: A :class:`.MapperExtension` instance or
-           list of :class:`.MapperExtension`
-           instances which will be applied to all operations by this
-           :class:`.Mapper`.  **Deprecated.**  Please see :class:`.MapperEvents`.
+           list of :class:`.MapperExtension` instances which will be applied
+           to all operations by this :class:`.Mapper`.  **Deprecated.**
+           Please see :class:`.MapperEvents`.
 
         :param include_properties: An inclusive list or set of string column
           names to map.
 
         :param inherits: A mapped class or the corresponding :class:`.Mapper`
           of one indicating a superclass to which this :class:`.Mapper`
-          should *inherit* from.   The mapped class here must be a subclass of the
-          other mapper's class.   When using Declarative, this argument
+          should *inherit* from.   The mapped class here must be a subclass
+          of the other mapper's class.   When using Declarative, this argument
           is passed automatically as a result of the natural class
           hierarchy of the declared classes.
 
            ordering.
 
         :param passive_updates: Indicates UPDATE behavior of foreign key
-           columns when a primary key column changes on a joined-table inheritance
-           mapping.   Defaults to ``True``.
+           columns when a primary key column changes on a joined-table
+           inheritance mapping.   Defaults to ``True``.
 
            When True, it is assumed that ON UPDATE CASCADE is configured on
            the foreign key in the database, and that the database will handle
            that will be used to keep a running version id of mapped entities
            in the database.  This is used during save operations to ensure that
            no other thread or process has updated the instance during the
-           lifetime of the entity, else a :class:`~sqlalchemy.orm.exc.StaleDataError`
-           exception is
+           lifetime of the entity, else a
+           :class:`~sqlalchemy.orm.exc.StaleDataError` exception is
            thrown.  By default the column must be of :class:`.Integer` type,
            unless ``version_id_generator`` specifies a new generation
            algorithm.
     """
     return Mapper(class_, local_table, *args, **params)
 
+
 def synonym(name, map_column=False, descriptor=None,
                         comparator_factory=None, doc=None):
     """Denote an attribute name as a synonym to a mapped property.
                             comparator_factory=comparator_factory,
                             doc=doc)
 
+
 def comparable_property(comparator_factory, descriptor=None):
     """Provides a method of applying a :class:`.PropComparator`
     to any Python descriptor attribute.
             id = Column(Integer, primary_key=True)
             word = Column(String)
             word_insensitive = comparable_property(lambda prop, mapper:
-                                    CaseInsensitiveComparator(mapper.c.word, mapper)
-                                )
+                            CaseInsensitiveComparator(mapper.c.word, mapper)
+                        )
 
 
     A mapping like the above allows the ``word_insensitive`` attribute
     """
     return ComparableProperty(comparator_factory, descriptor)
 
+
 @sa_util.deprecated("0.7", message=":func:`.compile_mappers` "
                             "is renamed to :func:`.configure_mappers`")
 def compile_mappers():
-    """Initialize the inter-mapper relationships of all mappers that have been defined."""
+    """Initialize the inter-mapper relationships of all mappers that have
+    been defined.
 
+    """
     configure_mappers()
 
+
 def clear_mappers():
     """Remove all mappers from all classes.
 
     finally:
         mapperlib._CONFIGURE_MUTEX.release()
 
+
 def joinedload(*keys, **kw):
     """Return a ``MapperOption`` that will convert the property of the given
     name or series of mapped attributes into an joined eager load.
        it **does not affect the query results**.   An :meth:`.Query.order_by`
        or :meth:`.Query.filter` call **cannot** reference these aliased
        tables - so-called "user space" joins are constructed using
-       :meth:`.Query.join`.   The rationale for this is that :func:`joinedload` is only
-       applied in order to affect how related objects or collections are loaded
-       as an optimizing detail - it can be added or removed with no impact
-       on actual results.   See the section :ref:`zen_of_eager_loading` for
-       a detailed description of how this is used, including how to use a single
-       explicit JOIN for filtering/ordering and eager loading simultaneously.
+       :meth:`.Query.join`.   The rationale for this is that
+       :func:`joinedload` is only applied in order to affect how related
+       objects or collections are loaded as an optimizing detail - it can be
+       added or removed with no impact on actual results.   See the section
+       :ref:`zen_of_eager_loading` for a detailed description of how this is
+       used, including how to use a single explicit JOIN for
+       filtering/ordering and eager loading simultaneously.
 
     See also:  :func:`subqueryload`, :func:`lazyload`
 
     else:
         return strategies.EagerLazyOption(keys, lazy='joined')
 
+
 def joinedload_all(*keys, **kw):
     """Return a ``MapperOption`` that will convert all properties along the
     given dot-separated path or series of mapped attributes
 
         query.options(joinedload_all('orders.items.keywords'))...
 
-    will set all of ``orders``, ``orders.items``, and ``orders.items.keywords`` to
-    load in one joined eager load.
+    will set all of ``orders``, ``orders.items``, and
+    ``orders.items.keywords`` to load in one joined eager load.
 
     Individual descriptors are accepted as arguments as well::
 
     """A synonym for :func:`joinedload()`."""
     return joinedload(*args, **kwargs)
 
+
 def eagerload_all(*args, **kwargs):
     """A synonym for :func:`joinedload_all()`"""
     return joinedload_all(*args, **kwargs)
 
+
 def subqueryload(*keys):
     """Return a ``MapperOption`` that will convert the property
     of the given name or series of mapped attributes
     """
     return strategies.EagerLazyOption(keys, lazy="subquery")
 
+
 def subqueryload_all(*keys):
     """Return a ``MapperOption`` that will convert all properties along the
     given dot-separated path or series of mapped attributes
 
         query.options(subqueryload_all('orders.items.keywords'))...
 
-    will set all of ``orders``, ``orders.items``, and ``orders.items.keywords`` to
-    load in one subquery eager load.
+    will set all of ``orders``, ``orders.items``, and
+    ``orders.items.keywords`` to load in one subquery eager load.
 
     Individual descriptors are accepted as arguments as well::
 
     """
     return strategies.EagerLazyOption(keys, lazy="subquery", chained=True)
 
+
 def lazyload(*keys):
     """Return a ``MapperOption`` that will convert the property of the given
     name or series of mapped attributes into a lazy load.
     """
     return strategies.EagerLazyOption(keys, lazy=True)
 
+
 def lazyload_all(*keys):
     """Return a ``MapperOption`` that will convert all the properties
     along the given dot-separated path or series of mapped attributes
     """
     return strategies.EagerLazyOption(keys, lazy=True, chained=True)
 
+
 def noload(*keys):
     """Return a ``MapperOption`` that will convert the property of the
     given name or series of mapped attributes into a non-load.
     """
     return strategies.EagerLazyOption(keys, lazy=None)
 
+
 def immediateload(*keys):
     """Return a ``MapperOption`` that will convert the property of the given
     name or series of mapped attributes into an immediate load.
     """
     return strategies.EagerLazyOption(keys, lazy='immediate')
 
+
 def contains_alias(alias):
     """Return a :class:`.MapperOption` that will indicate to the query that
     the main table has been aliased.
     """
     return AliasOption(alias)
 
+
 def contains_eager(*keys, **kwargs):
     """Return a ``MapperOption`` that will indicate to the query that
     the given attribute should be eagerly loaded from columns currently
             propagate_to_loaders=False, chained=True), \
         strategies.LoadEagerFromAliasOption(keys, alias=alias, chained=True)
 
+
 def defer(*key):
     """Return a :class:`.MapperOption` that will convert the column property
     of the given name into a deferred load.
     """
     return strategies.DeferredOption(key, defer=True)
 
+
 def undefer(*key):
     """Return a :class:`.MapperOption` that will convert the column property
     of the given name into a non-deferred (regular column) load.
 
         from sqlalchemy.orm import undefer
 
-        query(MyClass).options(undefer("attribute_one"),
-                                undefer("attribute_two"))
+        query(MyClass).options(
+                    undefer("attribute_one"),
+                    undefer("attribute_two"))
 
     A class bound descriptor is also accepted::
 
         query(MyClass).options(
-                            undefer(MyClass.attribute_one),
-                            undefer(MyClass.attribute_two))
+                    undefer(MyClass.attribute_one),
+                    undefer(MyClass.attribute_two))
 
     A "path" can be specified onto a related or collection object using a
     dotted name. The :func:`.orm.undefer` option will be applied to that
     object when loaded::
 
         query(MyClass).options(
-                            undefer("related.attribute_one"),
-                            undefer("related.attribute_two"))
+                    undefer("related.attribute_one"),
+                    undefer("related.attribute_two"))
 
     To specify a path via class, send multiple arguments::
 
         query(MyClass).options(
-                            undefer(MyClass.related, MyOtherClass.attribute_one),
-                            undefer(MyClass.related, MyOtherClass.attribute_two))
+                    undefer(MyClass.related, MyOtherClass.attribute_one),
+                    undefer(MyClass.related, MyOtherClass.attribute_two))
 
     See also:
 
     """
     return strategies.DeferredOption(key, defer=False)
 
+
 def undefer_group(name):
-    """Return a :class:`.MapperOption` that will convert the given group of deferred
-    column properties into a non-deferred (regular column) load.
+    """Return a :class:`.MapperOption` that will convert the given group of
+    deferred column properties into a non-deferred (regular column) load.
 
     Used with :meth:`.Query.options`.
 

File lib/sqlalchemy/orm/attributes.py

 )
 
 LOAD_AGAINST_COMMITTED = util.symbol("LOAD_AGAINST_COMMITTED",
-"""callables should use committed values as primary/foreign keys during a load""",
-canonical=32
+"""callables should use committed values as primary/foreign keys during a load
+""", canonical=32
 )
 
 # pre-packaged sets of flags used as inputs
 
 inspection._self_inspects(QueryableAttribute)
 
+
 class InstrumentedAttribute(QueryableAttribute):
     """Class bound instrumented attribute which adds descriptor methods."""
 
         if self._supports_population and self.key in dict_:
             return dict_[self.key]
         else:
-            return self.impl.get(instance_state(instance),dict_)
+            return self.impl.get(instance_state(instance), dict_)
+
 
 def create_proxied_attribute(descriptor):
     """Create an QueryableAttribute / user descriptor hybrid.
             return self._comparator
 
         def adapted(self, adapter):
-            """Proxy adapted() for the use case of AliasedClass calling adapted."""
+            """Proxy adapted() for the use case of AliasedClass calling
+            adapted.
 
+            """
             return self.__class__(self.class_, self.key, self.descriptor,
                                        self._comparator,
                                        adapter)
                     attribute)
                     )
 
-
     Proxy.__name__ = type(descriptor).__name__ + 'Proxy'
 
     util.monkeypatch_proxied_specials(Proxy, type(descriptor),
                                       from_instance=descriptor)
     return Proxy
 
+
 class AttributeImpl(object):
     """internal implementation for instrumented attributes."""
 
 
     active_history = property(_get_active_history, _set_active_history)
 
-
     def hasparent(self, state, optimistic=False):
         """Return the boolean value of a `hasparent` flag attached to
         the given state.
         will also not have a `hasparent` flag.
 
         """
-        assert self.trackparent, "This AttributeImpl is not configured to track parents."
+        msg = "This AttributeImpl is not configured to track parents."
+        assert self.trackparent, msg
 
         return state.parents.get(id(self.parent_token), optimistic) \
                 is not False
         attribute represented by this ``InstrumentedAttribute``.
 
         """
-        assert self.trackparent, "This AttributeImpl is not configured to track parents."
+        msg = "This AttributeImpl is not configured to track parents."
+        assert self.trackparent, msg
 
         id_ = id(self.parent_token)
         if value:
 
             state.parents[id_] = False
 
-
     def set_callable(self, state, callable_):
         """Set a callable function for this attribute on the given object.
 
         state._commit(dict_, [self.key])
         return value
 
+
 class ScalarAttributeImpl(AttributeImpl):
     """represents a scalar value-holding InstrumentedAttribute."""
 
         self.property.columns[0].type
 
 
-
-
 class ScalarObjectAttributeImpl(ScalarAttributeImpl):
     """represents a scalar-holding InstrumentedAttribute,
        where the target object is also instrumented.
 
         return [(instance_state(o), o) for o in current]
 
-
     def fire_append_event(self, state, dict_, value, initiator):
         for fn in self.dispatch.append:
             value = fn(state, value, initiator or self)
 
         return getattr(user_data, '_sa_adapter')
 
+
 def backref_listeners(attribute, key, uselist):
     """Apply listeners to synchronize a two-way relationship."""
 
         "added", "unchanged", "deleted"
     ])
 
+
 class History(History):
     """A 3-tuple of added, unchanged and deleted values,
     representing the changes which have occurred on an instrumented
 
 HISTORY_BLANK = History(None, None, None)
 
+
 def get_history(obj, key, passive=PASSIVE_OFF):
     """Return a :class:`.History` record for the given object
     and attribute key.
 
     return get_state_history(instance_state(obj), key, passive)
 
+
 def get_state_history(state, key, passive=PASSIVE_OFF):
     return state.get_history(key, passive)
 
     state = instance_state(obj)
     return manager.has_parent(state, key, optimistic)
 
+
 def register_attribute(class_, key, **kw):
     comparator = kw.pop('comparator', None)
     parententity = kw.pop('parententity', None)
     register_attribute_impl(class_, key, **kw)
     return desc
 
+
 def register_attribute_impl(class_, key,
         uselist=False, callable_=None,
         useobject=False,
                                        typecallable=typecallable, **kw)
     elif useobject:
         impl = ScalarObjectAttributeImpl(class_, key, callable_,
-                                        dispatch,**kw)
+                                        dispatch, **kw)
     else:
         impl = ScalarAttributeImpl(class_, key, callable_, dispatch, **kw)
 
     manager.post_configure_attribute(key)
     return manager[key]
 
+
 def register_descriptor(class_, key, comparator=None,
                                 parententity=None, doc=None):
     manager = manager_of_class(class_)
     manager.instrument_attribute(key, descriptor)
     return descriptor
 
+
 def unregister_attribute(class_, key):
     manager_of_class(class_).uninstrument_attribute(key)
 
+
 def init_collection(obj, key):
     """Initialize a collection attribute and return the collection adapter.
 
     dict_ = state.dict
     return init_state_collection(state, dict_, key)
 
+
 def init_state_collection(state, dict_, key):
     """Initialize a collection attribute and return the collection adapter."""
 
     user_data = attr.initialize(state, dict_)
     return attr.get_collection(state, dict_, user_data)
 
+
 def set_committed_value(instance, key, value):
     """Set the value of an attribute with no history events.
 
     state, dict_ = instance_state(instance), instance_dict(instance)
     state.manager[key].impl.set_committed_value(state, dict_, value)
 
+
 def set_attribute(instance, key, value):
     """Set the value of an attribute, firing history events.
 
     state, dict_ = instance_state(instance), instance_dict(instance)
     state.manager[key].impl.set(state, dict_, value, None)
 
+
 def get_attribute(instance, key):
     """Get the value of an attribute, firing any callables required.
 
     state, dict_ = instance_state(instance), instance_dict(instance)
     return state.manager[key].impl.get(state, dict_)
 
+
 def del_attribute(instance, key):
     """Delete the value of an attribute, firing history events.
 
     state, dict_ = instance_state(instance), instance_dict(instance)
     state.manager[key].impl.delete(state, dict_)
 
+
 def flag_modified(instance, key):
     """Mark an attribute on an instance as 'modified'.
 
     state, dict_ = instance_state(instance), instance_dict(instance)
     impl = state.manager[key].impl
     state._modified_event(dict_, impl, NO_VALUE)
-

File lib/sqlalchemy/orm/collections.py

         else:
             return key[0]
 
+
 class _SerializableColumnGetter(object):
     """Column-based getter used in version 0.7.6 only.
 
         else:
             return key[0]
 
+
 class _SerializableColumnGetterV2(_PlainColumnGetter):
     """Updated serializable getter which deals with
     multi-table mapped classes.
     keyfunc = _PlainColumnGetter(cols)
     return lambda: MappedCollection(keyfunc)
 
+
 class _SerializableAttrGetter(object):
     def __init__(self, name):
         self.name = name
     def __reduce__(self):
         return _SerializableAttrGetter, (self.name, )
 
+
 def attribute_mapped_collection(attr_name):
     """A dictionary-based collection type with attribute-based keying.
 
     """
     return lambda: MappedCollection(keyfunc)
 
+
 class collection(object):
     """Decorators for entity collection classes.
 
 
     return getattr(collection, '_sa_adapter', None)
 
+
 def collection_iter(collection):
     """Iterate over an object supporting the @iterator or __iter__ protocols.
 
         for member in removals:
             existing_adapter.remove_with_event(member)
 
+
 def prepare_instrumentation(factory):
     """Prepare a callable for future use as a collection class factory.
 
 
     return factory
 
+
 def __converting_factory(original_factory):
     """Convert the type returned by collection factories on the fly.
 
         pass
     return wrapper
 
+
 def _instrument_class(cls):
     """Modify methods in a class and install instrumentation."""
 
 
     setattr(cls, '_sa_instrumented', id(cls))
 
+
 def _instrument_membership_mutator(method, before, argument, after):
     """Route method args and/or return value through the collection adapter."""
     # This isn't smart enough to handle @adds(1) for 'def fn(self, (a, b))'
         pass
     return wrapper
 
+
 def __set(collection, item, _sa_initiator=None):
     """Run set events, may eventually be inlined into decorators."""
 
             item = getattr(executor, 'fire_append_event')(item, _sa_initiator)
     return item
 
+
 def __del(collection, item, _sa_initiator=None):
     """Run del events, may eventually be inlined into decorators."""
     if _sa_initiator is not False:
         if executor:
             getattr(executor, 'fire_remove_event')(item, _sa_initiator)
 
+
 def __before_delete(collection, _sa_initiator=None):
     """Special method to run 'commit existing value' methods"""
     executor = getattr(collection, '_sa_adapter', None)
     if executor:
         getattr(executor, 'fire_pre_remove_event')(_sa_initiator)
 
+
 def _list_decorators():
     """Tailored instrumentation wrappers for any list-like class."""
 
     l.pop('_tidy')
     return l
 
+
 def _dict_decorators():
     """Tailored instrumentation wrappers for any dict-like mapping class."""
 
     import sets
     _set_binop_bases = (set, frozenset, sets.BaseSet)
 
+
 def _set_binops_check_strict(self, obj):
     """Allow only set, frozenset and self.__class__-derived
     objects in binops."""
     return isinstance(obj, _set_binop_bases + (self.__class__,))
 
+
 def _set_binops_check_loose(self, obj):
     """Allow anything set-like to participate in set binops."""
     return (isinstance(obj, _set_binop_bases + (self.__class__,)) or
        'remover': 'remove',
        'iterator': '__iter__', }
 
+
 class InstrumentedSet(set):
     """An instrumented version of the built-in set."""
 
        'remover': 'remove',
        'iterator': '__iter__', }
 
+
 class InstrumentedDict(dict):
     """An instrumented version of the built-in dict."""
 
     None: {}
     }
 
+
 class MappedCollection(dict):
     """A basic dictionary-based collection class.
 
 _instrument_class(MappedCollection)
 _instrument_class(InstrumentedList)
 _instrument_class(InstrumentedSet)
-

File lib/sqlalchemy/orm/dependency.py

                                         util as mapperutil
 from .interfaces import ONETOMANY, MANYTOONE, MANYTOMANY
 
+
 class DependencyProcessor(object):
     def __init__(self, prop):
         self.prop = prop
         """
         uow.register_preprocessor(self, True)
 
-
     def per_property_flush_actions(self, uow):
         after_save = unitofwork.ProcessAll(uow, self, False, True)
         before_delete = unitofwork.ProcessAll(uow, self, True, True)
                                         before_delete
                                         )
 
-
     def per_state_flush_actions(self, uow, states, isdelete):
         """establish actions and dependencies related to a flush.
 
             # detect if there's anything changed or loaded
             # by a preprocessor on this state/attribute.  if not,
             # we should be able to skip it entirely.
-            sum_ = state.manager[self.key].impl.get_all_pending(state, state.dict)
+            sum_ = state.manager[self.key].impl.get_all_pending(
+                state, state.dict)
 
             if not sum_:
                 continue
                                                 after_save, before_delete,
                                                 isdelete, childisdelete)
 
-
     def presort_deletes(self, uowcommit, states):
         return False
 
     def __repr__(self):
         return "%s(%s)" % (self.__class__.__name__, self.prop)
 
+
 class OneToManyDP(DependencyProcessor):
 
     def per_property_dependencies(self, uow, parent_saves,
                             uowcommit.register_object(child,
                                     operation="delete", prop=self.prop)
 
-
-
     def presort_saves(self, uowcommit, states):
         children_added = uowcommit.memo(('children_added', self), set)
 
                             self.parent,
                             self.prop.synchronize_pairs)
 
+
 class ManyToOneDP(DependencyProcessor):
     def __init__(self, prop):
         DependencyProcessor.__init__(self, prop)
                             continue
                         uowcommit.register_object(child, isdelete=True,
                                         operation="delete", prop=self.prop)
-                        for c, m, st_, dct_ in self.mapper.cascade_iterator(
-                                                            'delete', child):
+                        t = self.mapper.cascade_iterator('delete', child)
+                        for c, m, st_, dct_ in t:
                             uowcommit.register_object(
                                 st_, isdelete=True)
 
                             uowcommit.register_object(child, isdelete=True,
                                         operation="delete", prop=self.prop)
 
-                            for c, m, st_, dct_ in self.mapper.cascade_iterator(
-                                                            'delete', child):
-                                uowcommit.register_object(
-                                    st_,
-                                    isdelete=True)
+                            t = self.mapper.cascade_iterator('delete', child)
+                            for c, m, st_, dct_ in t:
+                                uowcommit.register_object(st_, isdelete=True)
 
     def process_deletes(self, uowcommit, states):
         if self.post_update and \
                             uowcommit,
                             False)
 
+
 class DetectKeySwitch(DependencyProcessor):
     """For many-to-one relationships with no one-to-many backref,
     searches for parents through the unit of work when a primary
             if result.supports_sane_multi_rowcount() and \
                         result.rowcount != len(secondary_delete):
                 raise exc.StaleDataError(
-                        "DELETE statement on table '%s' expected to delete %d row(s); "
-                        "Only %d were matched." %
-                        (self.secondary.description, len(secondary_delete),
-                        result.rowcount)
-                    )
+                    "DELETE statement on table '%s' expected to delete "
+                    "%d row(s); Only %d were matched." %
+                    (self.secondary.description, len(secondary_delete),
+                    result.rowcount)
+                )
 
         if secondary_update:
             associationrow = secondary_update[0]
             if result.supports_sane_multi_rowcount() and \
                         result.rowcount != len(secondary_update):
                 raise exc.StaleDataError(
-                        "UPDATE statement on table '%s' expected to update %d row(s); "
-                        "Only %d were matched." %
-                        (self.secondary.description, len(secondary_update),
-                        result.rowcount)
-                    )
+                    "UPDATE statement on table '%s' expected to update "
+                    "%d row(s); Only %d were matched." %
+                    (self.secondary.description, len(secondary_update),
+                    result.rowcount)
+                )
 
         if secondary_insert:
             statement = self.secondary.insert()
                             self.prop.synchronize_pairs)
 
 _direction_to_processor = {
-    ONETOMANY : OneToManyDP,
+    ONETOMANY: OneToManyDP,
     MANYTOONE: ManyToOneDP,
-    MANYTOMANY : ManyToManyDP,
+    MANYTOMANY: ManyToManyDP,
 }
-

File lib/sqlalchemy/orm/deprecated_interfaces.py

                     event.listen(self, "%s" % meth, ls_meth,
                                         raw=False, retval=True, propagate=True)
 
-
     def instrument_class(self, mapper, class_):
         """Receive a class when the mapper is first constructed, and has
         applied instrumentation to the mapped class.
 
         return EXT_CONTINUE
 
+
 class SessionExtension(object):
 
     """Base implementation for :class:`.Session` event hooks.
         Note that this may not be per-flush if a longer running
         transaction is ongoing."""
 
-    def before_flush( self, session, flush_context, instances):
+    def before_flush(self, session, flush_context, instances):
         """Execute before flush process has started.
 
         `instances` is an optional list of objects which were passed to
         occurred, depending on whether or not the flush started its own
         transaction or participated in a larger transaction. """
 
-    def after_begin( self, session, transaction, connection):
+    def after_begin(self, session, transaction, connection):
         """Execute after a transaction is begun on a connection
 
         `transaction` is the SessionTransaction. This method is called
 
         This is called after an add, delete or merge. """
 
-    def after_bulk_update( self, session, query, query_context, result):
+    def after_bulk_update(self, session, query, query_context, result):
         """Execute after a bulk update operation to the session.
 
         This is called after a session.query(...).update()
         `result` is the result object returned from the bulk operation.
         """
 
-    def after_bulk_delete( self, session, query, query_context, result):
+    def after_bulk_delete(self, session, query, query_context, result):
         """Execute after a bulk delete operation to the session.
 
         This is called after a session.query(...).delete()
 
         """
         return value
-
-

File lib/sqlalchemy/orm/descriptor_props.py

 from ..sql import expression
 properties = util.importlater('sqlalchemy.orm', 'properties')
 
+
 class DescriptorProperty(MapperProperty):
     """:class:`.MapperProperty` which proxies access to a
         user-defined descriptor."""
         if self.descriptor is None:
             def fset(obj, value):
                 setattr(obj, self.name, value)
+
             def fdel(obj):
                 delattr(obj, self.name)
+
             def fget(obj):
                 return getattr(obj, self.name)
 
                 # key not present.  Iterate through related
                 # attributes, retrieve their values.  This
                 # ensures they all load.
-                values = [getattr(instance, key) for key in self._attribute_keys]
+                values = [
+                    getattr(instance, key)
+                    for key in self._attribute_keys
+                ]
 
                 # current expected behavior here is that the composite is
                 # created on access if the object is persistent or if
             state.dict.pop(self.key, None)
 
         event.listen(self.parent, 'after_insert',
-                                    insert_update_handler, raw=True)
+            insert_update_handler, raw=True)
         event.listen(self.parent, 'after_update',
-                                    insert_update_handler, raw=True)
-        event.listen(self.parent, 'load', load_handler, raw=True, propagate=True)
-        event.listen(self.parent, 'refresh', load_handler, raw=True, propagate=True)
-        event.listen(self.parent, "expire", expire_handler, raw=True, propagate=True)
+            insert_update_handler, raw=True)
+        event.listen(self.parent, 'load',
+            load_handler, raw=True, propagate=True)
+        event.listen(self.parent, 'refresh',
+            load_handler, raw=True, propagate=True)
+        event.listen(self.parent, 'expire',
+            expire_handler, raw=True, propagate=True)
 
         # TODO: need a deserialize hook here
 
             )
         else:
             return attributes.History(
-                (),[self.composite_class(*added)], ()
+                (), [self.composite_class(*added)], ()
             )
 
     def _comparator_factory(self, mapper):
             if self.adapter:
                 # TODO: test coverage for adapted composite comparison
                 return expression.ClauseList(
-                            *[self.adapter(x) for x in self.prop._comparable_elements])
+                    *[self.adapter(x) for x in self.prop._comparable_elements])
             else:
                 return expression.ClauseList(*self.prop._comparable_elements)
 
             else:
                 values = other.__composite_values__()
             return sql.and_(
-                    *[a==b for a, b in zip(self.prop._comparable_elements, values)])
+                    *[a == b
+                      for a, b in zip(self.prop._comparable_elements, values)]
+                )
 
         def __ne__(self, other):
             return sql.not_(self.__eq__(other))
     def __str__(self):
         return str(self.parent.class_.__name__) + "." + self.key
 
+
 class ConcreteInheritedProperty(DescriptorProperty):
     """A 'do nothing' :class:`.MapperProperty` that disables
     an attribute on a concrete subclass that is only present
         class NoninheritedConcreteProp(object):
             def __set__(s, obj, value):
                 warn()
+
             def __delete__(s, obj):
                 warn()
+
             def __get__(s, obj, owner):
                 if obj is None:
                     return self.descriptor
 
         self.parent = parent
 
+
 class ComparableProperty(DescriptorProperty):
     """Instruments a Python property for use in query expressions."""
 

File lib/sqlalchemy/orm/dynamic.py

     )
 from .query import Query
 
+
 class DynaLoader(strategies.AbstractRelationshipLoader):
     def init_class_attribute(self, mapper):
         self.is_class_level = True
         if not self.uselist:
             raise exc.InvalidRequestError(
-                    "On relationship %s, 'dynamic' loaders cannot be used with "
-                    "many-to-one/one-to-one relationships and/or "
-                    "uselist=False." % self.parent_property)
+                "On relationship %s, 'dynamic' loaders cannot be used with "
+                "many-to-one/one-to-one relationships and/or "
+                "uselist=False." % self.parent_property)
         strategies._register_attribute(self,
             mapper,
             useobject=True,
 
 log.class_logger(DynaLoader)
 
+
 class DynamicAttributeImpl(attributes.AttributeImpl):
     uses_objects = True
     accepts_scalar_loader = False
             return
         self._set_iterable(state, dict_, value)
 
-
     def _set_iterable(self, state, dict_, iterable, adapter=None):
         collection_history = self._modified_event(state, dict_)
         new_values = list(iterable)
                                   c.deleted_items)
 
     def get_all_pending(self, state, dict_):
-        c = self._get_collection_history(state, attributes.PASSIVE_NO_INITIALIZE)
+        c = self._get_collection_history(
+            state, attributes.PASSIVE_NO_INITIALIZE)
         return [
                 (attributes.instance_state(x), x)
                 for x in
         if initiator is not self:
             self.fire_remove_event(state, dict_, value, initiator)
 
+
 class DynCollectionAdapter(object):
     """the dynamic analogue to orm.collections.CollectionAdapter"""
 
     def remove_without_event(self, item):
         pass
 
+
 class AppenderMixin(object):
     query_class = None
 
 
     def session(self):
         return self.__session()
-    session = property(session, lambda s, x:None)
+    session = property(session, lambda s, x: None)
 
     def __iter__(self):
         sess = self.__session()
     name = 'Appender' + cls.__name__
     return type(name, (AppenderMixin, cls), {'query_class': cls})
 
+
 class CollectionHistory(object):
     """Overrides AttributeHistory to receive append/remove events directly."""
 
             self.deleted_items = []
             self.added_items = []
             self.unchanged_items = []
-

File lib/sqlalchemy/orm/evaluator.py

 import operator
 from ..sql import operators
 
+
 class UnevaluatableError(Exception):
     pass
 
                                  'notilike_op', 'between_op', 'in_op',
                                  'notin_op', 'endswith_op', 'concat_op'))
 
+
 class EvaluatorCompiler(object):
     def process(self, clause):
         meth = getattr(self, "visit_%s" % clause.__visit_name__, None)
         return evaluate
 
     def visit_binary(self, clause):
-        eval_left,eval_right = map(self.process,
+        eval_left, eval_right = map(self.process,
                                 [clause.left, clause.right])
         operator = clause.operator
         if operator is operators.is_:

File lib/sqlalchemy/orm/events.py

 
         """
 
-
     def attribute_instrument(self, cls, key, inst):
         """Called when an attribute is instrumented."""
 
+
 class _InstrumentationEventsHold(object):
-    """temporary marker object used to transfer from _accept_with() to _listen()
-    on the InstrumentationEvents class.
+    """temporary marker object used to transfer from _accept_with() to
+    _listen() on the InstrumentationEvents class.
 
     """
     def __init__(self, class_):
     def _listen(cls, target, identifier, fn, raw=False, propagate=False):
         if not raw:
             orig_fn = fn
+
             def wrap(state, *arg, **kw):
                 return orig_fn(state.obj(), *arg, **kw)
             fn = wrap
 
     @classmethod
     def _remove(cls, identifier, target, fn):
-        raise NotImplementedError("Removal of instance events not yet implemented")
+        msg = "Removal of instance events not yet implemented"
+        raise NotImplementedError(msg)
 
     @classmethod
     def _clear(cls):
 
         """
 
+
 class _EventsHold(object):
     """Hold onto listeners against unmapped, uninstrumented classes.
 
                         subject.dispatch._listen(subject, ident,
                                                         fn, raw, propagate)
 
+
 class _InstanceEventsHold(_EventsHold):
     all_holds = weakref.WeakKeyDictionary()
 
 
         # associate the listener function with SomeMappedClass,
         # to execute during the "before_insert" hook
-        event.listen(SomeMappedClass, 'before_insert', my_before_insert_listener)
+        event.listen(
+            SomeMappedClass, 'before_insert', my_before_insert_listener)
 
     Available targets include mapped classes, instances of
     :class:`.Mapper` (i.e. returned by :func:`.mapper`,
             if not raw:
                 meth = getattr(cls, identifier)
                 try:
-                    target_index = inspect.getargspec(meth)[0].index('target') - 1
+                    target_index = \
+                        inspect.getargspec(meth)[0].index('target') - 1
                 except ValueError:
                     target_index = None
 
             wrapped_fn = fn
+
             def wrap(*arg, **kw):
                 if not raw and target_index is not None:
                     arg = list(arg)
         """Called when the mapper for the class is fully configured.
 
         This event is the latest phase of mapper construction, and
-        is invoked when the mapped classes are first used, so that relationships
-        between mappers can be resolved.   When the event is called,
-        the mapper should be in its final state.
+        is invoked when the mapped classes are first used, so that
+        relationships between mappers can be resolved.   When the event is
+        called, the mapper should be in its final state.
 
         While the configuration event normally occurs automatically,
         it can be forced to occur ahead of time, in the case where the event
 
         Theoretically this event is called once per
         application, but is actually called any time new mappers
-        have been affected by a :func:`.orm.configure_mappers` call.   If new mappings
-        are constructed after existing ones have already been used,
-        this event can be called again.
+        have been affected by a :func:`.orm.configure_mappers`
+        call.   If new mappings are constructed after existing ones have
+        already been used, this event can be called again.
 
         """
 
 
         """
 
-
     def populate_instance(self, mapper, context, row,
                             target, **flags):
         """Receive an instance before that instance has
         .. warning::
             Mapper-level flush events are designed to operate **on attributes
             local to the immediate object being handled
-            and via SQL operations with the given** :class:`.Connection` **only.**
-            Handlers here should **not** make alterations to the state of
-            the :class:`.Session` overall, and in general should not
-            affect any :func:`.relationship` -mapped attributes, as
-            session cascade rules will not function properly, nor is it
-            always known if the related class has already been handled.
-            Operations that **are not supported in mapper events** include:
+            and via SQL operations with the given**
+            :class:`.Connection` **only.** Handlers here should **not** make
+            alterations to the state of the :class:`.Session` overall, and
+            in general should not affect any :func:`.relationship` -mapped
+            attributes, as session cascade rules will not function properly,
+            nor is it always known if the related class has already been
+            handled. Operations that **are not supported in mapper
+            events** include:
 
             * :meth:`.Session.add`
             * :meth:`.Session.delete`
             * Mapped collection append, add, remove, delete, discard, etc.
-            * Mapped relationship attribute set/del events, i.e. ``someobject.related = someotherobject``
+            * Mapped relationship attribute set/del events,
+              i.e. ``someobject.related = someotherobject``
 
             Operations which manipulate the state of the object
             relative to other objects are better handled:
 
-            * In the ``__init__()`` method of the mapped object itself, or another method
-              designed to establish some particular state.
+            * In the ``__init__()`` method of the mapped object itself, or
+              another method designed to establish some particular state.
             * In a ``@validates`` handler, see :ref:`simple_validators`
             * Within the  :meth:`.SessionEvents.before_flush` event.
 
         .. warning::
             Mapper-level flush events are designed to operate **on attributes
             local to the immediate object being handled
-            and via SQL operations with the given** :class:`.Connection` **only.**
-            Handlers here should **not** make alterations to the state of
-            the :class:`.Session` overall, and in general should not
-            affect any :func:`.relationship` -mapped attributes, as
-            session cascade rules will not function properly, nor is it
-            always known if the related class has already been handled.
-            Operations that **are not supported in mapper events** include:
+            and via SQL operations with the given**
+            :class:`.Connection` **only.** Handlers here should **not** make
+            alterations to the state of the :class:`.Session` overall, and in
+            general should not affect any :func:`.relationship` -mapped
+            attributes, as session cascade rules will not function properly,
+            nor is it always known if the related class has already been
+            handled. Operations that **are not supported in mapper
+            events** include:
 
             * :meth:`.Session.add`
             * :meth:`.Session.delete`
             * Mapped collection append, add, remove, delete, discard, etc.
-            * Mapped relationship attribute set/del events, i.e. ``someobject.related = someotherobject``
+            * Mapped relationship attribute set/del events,
+              i.e. ``someobject.related = someotherobject``
 
             Operations which manipulate the state of the object
             relative to other objects are better handled:
 
-            * In the ``__init__()`` method of the mapped object itself, or another method
-              designed to establish some particular state.
+            * In the ``__init__()`` method of the mapped object itself,
+              or another method designed to establish some particular state.
             * In a ``@validates`` handler, see :ref:`simple_validators`
             * Within the  :meth:`.SessionEvents.before_flush` event.
 
         .. warning::
             Mapper-level flush events are designed to operate **on attributes
             local to the immediate object being handled
-            and via SQL operations with the given** :class:`.Connection` **only.**
-            Handlers here should **not** make alterations to the state of
-            the :class:`.Session` overall, and in general should not
+            and via SQL operations with the given** :class:`.Connection`
+            **only.** Handlers here should **not** make alterations to the
+            state of the :class:`.Session` overall, and in general should not
             affect any :func:`.relationship` -mapped attributes, as
             session cascade rules will not function properly, nor is it
             always known if the related class has already been handled.
             * :meth:`.Session.add`
             * :meth:`.Session.delete`
             * Mapped collection append, add, remove, delete, discard, etc.
-            * Mapped relationship attribute set/del events, i.e. ``someobject.related = someotherobject``
+            * Mapped relationship attribute set/del events,
+              i.e. ``someobject.related = someotherobject``
 
             Operations which manipulate the state of the object
             relative to other objects are better handled:
 
-            * In the ``__init__()`` method of the mapped object itself, or another method
-              designed to establish some particular state.
+            * In the ``__init__()`` method of the mapped object itself,
+              or another method designed to establish some particular state.
             * In a ``@validates`` handler, see :ref:`simple_validators`
             * Within the  :meth:`.SessionEvents.before_flush` event.
 
         .. warning::
             Mapper-level flush events are designed to operate **on attributes
             local to the immediate object being handled
-            and via SQL operations with the given** :class:`.Connection` **only.**
-            Handlers here should **not** make alterations to the state of
-            the :class:`.Session` overall, and in general should not
+            and via SQL operations with the given** :class:`.Connection`
+            **only.** Handlers here should **not** make alterations to the
+            state of the :class:`.Session` overall, and in general should not
             affect any :func:`.relationship` -mapped attributes, as
             session cascade rules will not function properly, nor is it
             always known if the related class has already been handled.
             * :meth:`.Session.add`
             * :meth:`.Session.delete`
             * Mapped collection append, add, remove, delete, discard, etc.
-            * Mapped relationship attribute set/del events, i.e. ``someobject.related = someotherobject``
+            * Mapped relationship attribute set/del events,
+              i.e. ``someobject.related = someotherobject``
 
             Operations which manipulate the state of the object
             relative to other objects are better handled:
 
-            * In the ``__init__()`` method of the mapped object itself, or another method
-              designed to establish some particular state.
+            * In the ``__init__()`` method of the mapped object itself,
+              or another method designed to establish some particular state.
             * In a ``@validates`` handler, see :ref:`simple_validators`
             * Within the  :meth:`.SessionEvents.before_flush` event.
 
         .. warning::
             Mapper-level flush events are designed to operate **on attributes
             local to the immediate object being handled
-            and via SQL operations with the given** :class:`.Connection` **only.**
-            Handlers here should **not** make alterations to the state of
-            the :class:`.Session` overall, and in general should not
+            and via SQL operations with the given** :class:`.Connection`
+            **only.** Handlers here should **not** make alterations to the
+            state of the :class:`.Session` overall, and in general should not
             affect any :func:`.relationship` -mapped attributes, as
             session cascade rules will not function properly, nor is it
             always known if the related class has already been handled.
             * :meth:`.Session.add`
             * :meth:`.Session.delete`
             * Mapped collection append, add, remove, delete, discard, etc.
-            * Mapped relationship attribute set/del events, i.e. ``someobject.related = someotherobject``
+            * Mapped relationship attribute set/del events,
+              i.e. ``someobject.related = someotherobject``
 
             Operations which manipulate the state of the object
             relative to other objects are better handled:
 
-            * In the ``__init__()`` method of the mapped object itself, or another method
-              designed to establish some particular state.
+            * In the ``__init__()`` method of the mapped object itself,
+              or another method designed to establish some particular state.
             * In a ``@validates`` handler, see :ref:`simple_validators`
             * Within the  :meth:`.SessionEvents.before_flush` event.
 
         .. warning::
             Mapper-level flush events are designed to operate **on attributes
             local to the immediate object being handled
-            and via SQL operations with the given** :class:`.Connection` **only.**
-            Handlers here should **not** make alterations to the state of
-            the :class:`.Session` overall, and in general should not
+            and via SQL operations with the given** :class:`.Connection`
+            **only.** Handlers here should **not** make alterations to the
+            state of the :class:`.Session` overall, and in general should not
             affect any :func:`.relationship` -mapped attributes, as
             session cascade rules will not function properly, nor is it
             always known if the related class has already been handled.
             * :meth:`.Session.add`
             * :meth:`.Session.delete`
             * Mapped collection append, add, remove, delete, discard, etc.
-            * Mapped relationship attribute set/del events, i.e. ``someobject.related = someotherobject``
+            * Mapped relationship attribute set/del events,
+              i.e. ``someobject.related = someotherobject``
 
             Operations which manipulate the state of the object
             relative to other objects are better handled:
 
-            * In the ``__init__()`` method of the mapped object itself, or another method
-              designed to establish some particular state.
+            * In the ``__init__()`` method of the mapped object itself,
+              or another method designed to establish some particular state.
             * In a ``@validates`` handler, see :ref:`simple_validators`
             * Within the  :meth:`.SessionEvents.before_flush` event.
 
 
     @classmethod
     def _remove(cls, identifier, target, fn):
-        raise NotImplementedError("Removal of mapper events not yet implemented")
+        "Removal of mapper events not yet implemented"
+        raise NotImplementedError(msg)
+
 
 class _MapperEventsHold(_EventsHold):
     all_holds = weakref.WeakKeyDictionary()
 
     dispatch = event.dispatcher(HoldMapperEvents)
 
+
 class SessionEvents(event.Events):
     """Define events specific to :class:`.Session` lifecycle.
 
     globally.
 
     """
-
     @classmethod
     def _accept_with(cls, target):
         if isinstance(target, orm.scoped_session):
                             "requires that its creation callable "
                             "is associated with the Session class.")
 
-
         if isinstance(target, orm.sessionmaker):
             return target.class_
         elif isinstance(target, type):
 
     @classmethod
     def _remove(cls, identifier, target, fn):
-        raise NotImplementedError("Removal of session events not yet implemented")
+        msg = "Removal of session events not yet implemented"
+        raise NotImplementedError(msg)
 
     def after_transaction_create(self, session, transaction):
         """Execute when a new :class:`.SessionTransaction` is created.
                     session.execute("select * from some_table")
 
         :param session: The target :class:`.Session`.
-        :param previous_transaction: The :class:`.SessionTransaction` transactional
-         marker object which was just closed.   The current :class:`.SessionTransaction`
-         for the given :class:`.Session` is available via the
-         :attr:`.Session.transaction` attribute.
+        :param previous_transaction: The :class:`.SessionTransaction`
+        transactional marker object which was just closed.   The current
+        :class:`.SessionTransaction` for the given :class:`.Session` is
+        available via the :attr:`.Session.transaction` attribute.
 
         .. versionadded:: 0.7.3
 
         """
 
-    def before_flush( self, session, flush_context, instances):
+    def before_flush(self, session, flush_context, instances):
         """Execute before flush process has started.
 
         :param session: The target :class:`.Session`.
          which handles the details of the flush.
         """
 
-    def after_begin( self, session, transaction, connection):
+    def after_begin(self, session, transaction, connection):
         """Execute after a transaction is begun on a connection
 
         :param session: The target :class:`.Session`.
 
         """
 
-    def after_bulk_update( self, session, query, query_context, result):
+    def after_bulk_update(self, session, query, query_context, result):
         """Execute after a bulk update operation to the session.
 
         This is called as a result of the :meth:`.Query.update` method.
 
         """
 
-    def after_bulk_delete( self, session, query, query_context, result):
+    def after_bulk_delete(self, session, query, query_context, result):
         """Execute after a bulk delete operation to the session.
 
         This is called as a result of the :meth:`.Query.delete` method.
 
         if not raw or not retval:
             orig_fn = fn
+
             def wrap(target, value, *arg):
                 if not raw:
                     target = target.obj()
 
     @classmethod
     def _remove(cls, identifier, target, fn):
-        raise NotImplementedError("Removal of attribute events not yet implemented")
+        msg = "Removal of attribute events not yet implemented"
+        raise NotImplementedError(msg)
 
     def append(self, target, value, initiator):
         """Receive a collection append event.
          the given value, or a new effective value, should be returned.
 
         """
-

File lib/sqlalchemy/orm/exc.py

 NO_STATE = (AttributeError, KeyError)
 """Exception types that may be raised by instrumentation implementations."""
 
+
 class StaleDataError(sa_exc.SQLAlchemyError):
     """An operation encountered database state that is unaccounted for.
 
 class UnmappedError(sa_exc.InvalidRequestError):
     """Base for exceptions that involve expected mappings not present."""
 
+
 class ObjectDereferencedError(sa_exc.SQLAlchemyError):
-    """An operation cannot complete due to an object being garbage collected."""
+    """An operation cannot complete due to an object being garbage
+    collected.
+
+    """
+
 
 class DetachedInstanceError(sa_exc.SQLAlchemyError):
     """An attempt to access unloaded attributes on a
     mapped instance that is detached."""
 
+
 class UnmappedInstanceError(UnmappedError):
     """An mapping operation was requested for an unknown instance."""
 
                 mapper = orm_util.class_mapper(type(obj))
                 name = _safe_cls_name(type(obj))
                 msg = ("Class %r is mapped, but this instance lacks "
-                       "instrumentation.  This occurs when the instance is created "
-                       "before sqlalchemy.orm.mapper(%s) was called." % (name, name))
+                       "instrumentation.  This occurs when the instance"
+                       "is created before sqlalchemy.orm.mapper(%s) "
+                       "was called." % (name, name))
             except UnmappedClassError:
                 msg = _default_unmapped(type(obj))
                 if isinstance(obj, type):
     def __reduce__(self):
         return self.__class__, (None, self.args[0])
 
+
 class UnmappedClassError(UnmappedError):
     """An mapping operation was requested for an unknown class."""
 
     def __reduce__(self):
         return self.__class__, (None, self.args[0])
 
+
 class ObjectDeletedError(sa_exc.InvalidRequestError):
     """A refresh operation failed to retrieve the database
     row corresponding to an object's known primary key identity.
     def __reduce__(self):
         return self.__class__, (None, self.args[0])
 
+
 class UnmappedColumnError(sa_exc.InvalidRequestError):
     """Mapping operation was requested on an unknown column."""
 
             cls_name = repr(cls)
     return cls_name
 
+
 def _default_unmapped(cls):
     try:
         mappers = attributes.manager_of_class(cls).mappers