]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
Documentation markup and a few typos
authorLele Gaifax <lele@metapensiero.it>
Sat, 15 Dec 2007 09:50:35 +0000 (09:50 +0000)
committerLele Gaifax <lele@metapensiero.it>
Sat, 15 Dec 2007 09:50:35 +0000 (09:50 +0000)
lib/sqlalchemy/orm/session.py

index ce4e20bc930b399083d4204001bba5b108210aff..d6d1d1ff6ba8d1ff45496dc8ddca93d62ec3e6e0 100644 (file)
@@ -16,115 +16,115 @@ __all__ = ['Session', 'SessionTransaction', 'SessionExtension']
 
 def sessionmaker(bind=None, class_=None, autoflush=True, transactional=True, **kwargs):
     """Generate a custom-configured [sqlalchemy.orm.session#Session] class.
-    
+
     The returned object is a subclass of ``Session``, which, when instantiated with no
-    arguments, uses the
-    keyword arguments configured here as its constructor arguments.  It is intended
-    that the `sessionmaker()` function be called within the global scope of an application,
-    and the returned class be made available to the rest of the application as the 
-    single class used to instantiate sessions.
-    
+    arguments, uses the keyword arguments configured here as its constructor arguments.
+
+    It is intended that the `sessionmaker()` function be called within the global scope
+    of an application, and the returned class be made available to the rest of the
+    application as the single class used to instantiate sessions.
+
     e.g.::
-    
+
         # global scope
         Session = sessionmaker(autoflush=False)
-        
+
         # later, in a local scope, create and use a session:
         sess = Session()
-    
+
     Any keyword arguments sent to the constructor itself will override the "configured"
     keywords::
-    
+
         Session = sessionmaker()
-        
+
         # bind an individual session to a connection
         sess = Session(bind=connection)
-        
-    The class also includes a special classmethod ``configure()``, which allows 
+
+    The class also includes a special classmethod ``configure()``, which allows
     additional configurational options to take place after the custom ``Session``
-    class has been generated.  This is useful particularly for defining the 
+    class has been generated.  This is useful particularly for defining the
     specific ``Engine`` (or engines) to which new instances of ``Session``
     should be bound::
-    
+
         Session = sessionmaker()
         Session.configure(bind=create_engine('sqlite:///foo.db'))
-        
+
         sess = Session()
-    
+
     The function features a single keyword argument of its own, `class_`, which
     may be used to specify an alternate class other than ``sqlalchemy.orm.session.Session``
-    which should be used by the returned class.  All other keyword arguments sent to 
+    which should be used by the returned class.  All other keyword arguments sent to
     `sessionmaker()` are passed through to the instantiated `Session()` object.
     """
-    
+
     kwargs['bind'] = bind
     kwargs['autoflush'] = autoflush
     kwargs['transactional'] = transactional
 
     if class_ is None:
         class_ = Session
-        
+
     class Sess(class_):
         def __init__(self, **local_kwargs):
             for k in kwargs:
                 local_kwargs.setdefault(k, kwargs[k])
             super(Sess, self).__init__(**local_kwargs)
-        
+
         def configure(self, **new_kwargs):
             """(re)configure the arguments for this sessionmaker.
-            
+
             e.g.
                 Session = sessionmaker()
                 Session.configure(bind=create_engine('sqlite://'))
             """
-            
+
             kwargs.update(new_kwargs)
         configure = classmethod(configure)
-        
+
     return Sess
 
 class SessionExtension(object):
-    """an extension hook object for Sessions.  Subclasses may be installed into a Session
+    """An extension hook object for Sessions.  Subclasses may be installed into a Session
     (or sessionmaker) using the ``extension`` keyword argument.
     """
-    
+
     def before_commit(self, session):
-        """execute right before commit is called.
-        
+        """Execute right before commit is called.
+
         Note that this may not be per-flush if a longer running transaction is ongoing."""
 
     def after_commit(self, session):
-        """execute after a commit has occured.
-        
+        """Execute after a commit has occured.
+
         Note that this may not be per-flush if a longer running transaction is ongoing."""
 
     def after_rollback(self, session):
-        """execute after a rollback has occured.
+        """Execute after a rollback has occured.
 
         Note that this may not be per-flush if a longer running transaction is ongoing."""
 
     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 the ``flush()``
+        """Execute before flush process has started.
+
+        `instances` is an optional list of objects which were passed to the ``flush()``
         method.
         """
 
     def after_flush(self, session, flush_context):
-        """execute after flush has completed, but before commit has been called.
-        
+        """Execute after flush has completed, but before commit has been called.
+
         Note that the session's state is still in pre-flush, i.e. 'new', 'dirty',
         and 'deleted' lists still show pre-flush state as well as the history
         settings on instance attributes."""
-        
+
     def after_flush_postexec(self, session, flush_context):
-        """execute after flush has completed, and after the post-exec state occurs.
-        
-        this will be when the 'new', 'dirty', and 'deleted' lists are in their final 
+        """Execute after flush has completed, and after the post-exec state occurs.
+
+        This will be when the 'new', 'dirty', and 'deleted' lists are in their final
         state.  An actual commit() may or may not have occured, depending on whether or not
         the flush started its own transaction or participated in a larger transaction.
         """
-        
+
 class SessionTransaction(object):
     """Represents a Session-level Transaction.
 
@@ -133,9 +133,9 @@ class SessionTransaction(object):
     use.
 
     Direct usage of ``SessionTransaction`` is not necessary as of
-    SQLAlchemy 0.4; use the ``begin()`` and ``commit()`` methods on 
+    SQLAlchemy 0.4; use the ``begin()`` and ``commit()`` methods on
     ``Session`` itself.
-    
+
     The ``SessionTransaction`` object is **not** threadsafe.
     """
 
@@ -156,7 +156,7 @@ class SessionTransaction(object):
     def add(self, bind):
         if self.__parent is not None:
             return self.__parent.add(bind)
-            
+
         if bind.engine in self.__connections:
             raise exceptions.InvalidRequestError("Session already has a Connection associated for the given %sEngine" % (isinstance(bind, engine.Connection) and "Connection's " or ""))
         return self.get_or_add(bind)
@@ -166,12 +166,12 @@ class SessionTransaction(object):
             return self.__parent._connection_dict()
         else:
             return self.__connections
-            
+
     def get_or_add(self, bind):
         if self.__parent is not None:
             if not self.nested:
                 return self.__parent.get_or_add(bind)
-            
+
             if bind in self.__connections:
                 return self.__connections[bind][0]
 
@@ -182,7 +182,7 @@ class SessionTransaction(object):
                 return conn
         elif bind in self.__connections:
             return self.__connections[bind][0]
-            
+
         if not isinstance(bind, engine.Connection):
             e = bind
             c = bind.contextual_connect()
@@ -206,7 +206,7 @@ class SessionTransaction(object):
 
         if self.session.extension is not None:
             self.session.extension.before_commit(self.session)
-            
+
         if self.autoflush:
             self.session.flush()
 
@@ -226,7 +226,7 @@ class SessionTransaction(object):
     def rollback(self):
         if self.__parent is not None and not self.nested:
             return self.__parent.rollback()
-        
+
         for t in util.Set(self.__connections.values()):
             t[1].rollback()
 
@@ -235,7 +235,7 @@ class SessionTransaction(object):
 
         self.close()
         return self.__parent
-        
+
     def close(self):
         if self.__parent is not None:
             return
@@ -263,7 +263,7 @@ class Session(object):
     The Session is the front end to SQLAlchemy's **Unit of Work** implementation. The concept
     behind Unit of Work is to track modifications to a field of objects, and then be able to
     flush those changes to the database in a single operation.
-    
+
     SQLAlchemy's unit of work includes these functions:
 
     * The ability to track in-memory changes on scalar- and collection-based object
@@ -307,91 +307,91 @@ class Session(object):
 
     The session methods which control instance state include ``save()``, ``update()``,
     ``save_or_update()``, ``delete()``, ``merge()``, and ``expunge()``.
-    
+
     The Session object is **not** threadsafe, particularly during flush operations.  A session
     which is only read from (i.e. is never flushed) can be used by concurrent threads if it's
-    acceptable that some object instances may be loaded twice.  
-    
+    acceptable that some object instances may be loaded twice.
+
     The typical pattern to managing Sessions in a multi-threaded environment is either to use
     mutexes to limit concurrent access to one thread at a time, or more commonly to establish
-    a unique session for every thread, using a threadlocal variable.  SQLAlchemy provides 
+    a unique session for every thread, using a threadlocal variable.  SQLAlchemy provides
     a thread-managed Session adapter, provided by the [sqlalchemy.orm#scoped_session()] function.
     """
 
     def __init__(self, bind=None, autoflush=True, transactional=False, twophase=False, echo_uow=False, weak_identity_map=True, binds=None, extension=None):
         """Construct a new Session.
 
-            autoflush
-                when ``True``, all query operations will issue a ``flush()`` call to this
-                ``Session`` before proceeding. This is a convenience feature so that
-                ``flush()`` need not be called repeatedly in order for database queries to
-                retrieve results. It's typical that ``autoflush`` is used in conjunction with
-                ``transactional=True``, so that ``flush()`` is never called; you just call
-                ``commit()`` when changes are complete to finalize all changes to the
-                database.
-        
-            bind
-                an optional ``Engine`` or ``Connection`` to which this ``Session`` should be
-                bound. When specified, all SQL operations performed by this session will
-                execute via this connectable.
-                
-            binds
-                an optional dictionary, which contains more granular "bind" information than
-                the ``bind`` parameter provides. This dictionary can map individual ``Table``
-                instances as well as ``Mapper`` instances to individual ``Engine`` or
-                ``Connection`` objects. Operations which proceed relative to a particular
-                ``Mapper`` will consult this dictionary for the direct ``Mapper`` instance as
-                well as the mapper's ``mapped_table`` attribute in order to locate an
-                connectable to use. The full resolution is described in the ``get_bind()``
-                method of ``Session``. Usage looks like::
-                
-                    sess = Session(binds={
-                        SomeMappedClass : create_engine('postgres://engine1'),
-                        somemapper : create_engine('postgres://engine2'),
-                        some_table : create_engine('postgres://engine3'),
-                    })
-                    
-                Also see the ``bind_mapper()`` and ``bind_table()`` methods.
-            
-            echo_uow
-                When ``True``, configure Python logging to dump all unit-of-work
-                transactions. This is the equivalent of
-                ``logging.getLogger('sqlalchemy.orm.unitofwork').setLevel(logging.DEBUG)``.
-            
-            extension
-                an optional [sqlalchemy.orm.session#SessionExtension] instance, which will receive
-                pre- and post- commit and flush events, as well as a post-rollback event.  User-
-                defined code may be placed within these hooks using a user-defined subclass
-                of ``SessionExtension``.
-                
-            transactional
-                Set up this ``Session`` to automatically begin transactions. Setting this
-                flag to ``True`` is the rough equivalent of calling ``begin()`` after each
-                ``commit()`` operation, after each ``rollback()``, and after each
-                ``close()``. Basically, this has the effect that all session operations are
-                performed within the context of a transaction. Note that the ``begin()``
-                operation does not immediately utilize any connection resources; only when
-                connection resources are first required do they get allocated into a
-                transactional context.
-
-            twophase
-                when ``True``, all transactions will be started using
-                [sqlalchemy.engine_TwoPhaseTransaction]. During a ``commit()``, after
-                ``flush()`` has been issued for all attached databaes, the ``prepare()``
-                method on each database's ``TwoPhaseTransaction`` will be called. This allows
-                each database to roll back the entire transaction, before each transaction is
-                committed.
-
-            weak_identity_map
-                When set to the default value of ``False``, a weak-referencing map is used;
-                instances which are not externally referenced will be garbage collected
-                immediately. For dereferenced instances which have pending changes present,
-                the attribute management system will create a temporary strong-reference to
-                the object which lasts until the changes are flushed to the database, at which
-                point it's again dereferenced. Alternatively, when using the value ``True``,
-                the identity map uses a regular Python dictionary to store instances. The
-                session will maintain all instances present until they are removed using
-                expunge(), clear(), or purge().
+        autoflush
+            When ``True``, all query operations will issue a ``flush()`` call to this
+            ``Session`` before proceeding. This is a convenience feature so that
+            ``flush()`` need not be called repeatedly in order for database queries to
+            retrieve results. It's typical that ``autoflush`` is used in conjunction with
+            ``transactional=True``, so that ``flush()`` is never called; you just call
+            ``commit()`` when changes are complete to finalize all changes to the
+            database.
+
+        bind
+            An optional ``Engine`` or ``Connection`` to which this ``Session`` should be
+            bound. When specified, all SQL operations performed by this session will
+            execute via this connectable.
+
+        binds
+            An optional dictionary, which contains more granular "bind" information than
+            the ``bind`` parameter provides. This dictionary can map individual ``Table``
+            instances as well as ``Mapper`` instances to individual ``Engine`` or
+            ``Connection`` objects. Operations which proceed relative to a particular
+            ``Mapper`` will consult this dictionary for the direct ``Mapper`` instance as
+            well as the mapper's ``mapped_table`` attribute in order to locate an
+            connectable to use. The full resolution is described in the ``get_bind()``
+            method of ``Session``. Usage looks like::
+
+                sess = Session(binds={
+                    SomeMappedClass : create_engine('postgres://engine1'),
+                    somemapper : create_engine('postgres://engine2'),
+                    some_table : create_engine('postgres://engine3'),
+                })
+
+            Also see the ``bind_mapper()`` and ``bind_table()`` methods.
+
+        echo_uow
+            When ``True``, configure Python logging to dump all unit-of-work
+            transactions. This is the equivalent of
+            ``logging.getLogger('sqlalchemy.orm.unitofwork').setLevel(logging.DEBUG)``.
+
+        extension
+            An optional [sqlalchemy.orm.session#SessionExtension] instance, which will receive
+            pre- and post- commit and flush events, as well as a post-rollback event.  User-
+            defined code may be placed within these hooks using a user-defined subclass
+            of ``SessionExtension``.
+
+        transactional
+            Set up this ``Session`` to automatically begin transactions. Setting this
+            flag to ``True`` is the rough equivalent of calling ``begin()`` after each
+            ``commit()`` operation, after each ``rollback()``, and after each
+            ``close()``. Basically, this has the effect that all session operations are
+            performed within the context of a transaction. Note that the ``begin()``
+            operation does not immediately utilize any connection resources; only when
+            connection resources are first required do they get allocated into a
+            transactional context.
+
+        twophase
+            When ``True``, all transactions will be started using
+            [sqlalchemy.engine_TwoPhaseTransaction]. During a ``commit()``, after
+            ``flush()`` has been issued for all attached databases, the ``prepare()``
+            method on each database's ``TwoPhaseTransaction`` will be called. This allows
+            each database to roll back the entire transaction, before each transaction is
+            committed.
+
+        weak_identity_map
+            When set to the default value of ``False``, a weak-referencing map is used;
+            instances which are not externally referenced will be garbage collected
+            immediately. For dereferenced instances which have pending changes present,
+            the attribute management system will create a temporary strong-reference to
+            the object which lasts until the changes are flushed to the database, at which
+            point it's again dereferenced. Alternatively, when using the value ``True``,
+            the identity map uses a regular Python dictionary to store instances. The
+            session will maintain all instances present until they are removed using
+            expunge(), clear(), or purge().
         """
         self.echo_uow = echo_uow
         self.weak_identity_map = weak_identity_map
@@ -408,7 +408,7 @@ class Session(object):
         self.extension = extension
         self._query_cls = query.Query
         self._mapper_flush_opts = {}
-        
+
         if binds is not None:
             for mapperortable, value in binds.iteritems():
                 if isinstance(mapperortable, type):
@@ -417,11 +417,11 @@ class Session(object):
                 if isinstance(mapperortable, Mapper):
                     for t in mapperortable._all_tables:
                         self.__binds[t] = value
-                
+
         if self.transactional:
             self.begin()
         _sessions[self.hash_key] = self
-            
+
     def begin(self, **kwargs):
         """Begin a transaction on this Session."""
 
@@ -430,50 +430,51 @@ class Session(object):
         else:
             self.transaction = SessionTransaction(self, **kwargs)
         return self.transaction
-        
+
     create_transaction = begin
 
     def begin_nested(self):
-        """begin a 'nested' transaction on this Session.
-        
-        this utilizes a SAVEPOINT transaction for databases 
+        """Begin a `nested` transaction on this Session.
+
+        This utilizes a ``SAVEPOINT`` transaction for databases
         which support this feature.
         """
+
         return self.begin(nested=True)
-    
+
     def rollback(self):
-        """rollback the current transaction in progress.
-        
-        If no transaction is in progress, this method is a 
+        """Rollback the current transaction in progress.
+
+        If no transaction is in progress, this method is a
         pass-thru.
         """
-        
+
         if self.transaction is None:
             pass
         else:
             self.transaction = self.transaction.rollback()
         # TODO: we can rollback attribute values.  however
-        # we would want to expand attributes.py to be able to save *two* rollback points, one to the 
+        # we would want to expand attributes.py to be able to save *two* rollback points, one to the
         # last flush() and the other to when the object first entered the transaction.
         # [ticket:705]
         #attributes.rollback(*self.identity_map.values())
         if self.transaction is None and self.transactional:
             self.begin()
-            
+
     def commit(self):
-        """commit the current transaction in progress.
-        
+        """Commit the current transaction in progress.
+
         If no transaction is in progress, this method raises
-        an InvalidRequestError.  
-        
+        an InvalidRequestError.
+
         If the ``begin()`` method was called on this ``Session``
-        additional times subsequent to its first call, 
+        additional times subsequent to its first call,
         ``commit()`` will not actually commit, and instead
         pops an internal SessionTransaction off its internal stack
         of transactions.  Only when the "root" SessionTransaction
         is reached does an actual database-level commit occur.
-        
         """
+
         if self.transaction is None:
             if self.transactional:
                 self.begin()
@@ -484,7 +485,7 @@ class Session(object):
             self.transaction = self.transaction.commit()
         if self.transaction is None and self.transactional:
             self.begin()
-    
+
     def connection(self, mapper=None, **kwargs):
         """Return a ``Connection`` corresponding to this session's
         transactional context, if any.
@@ -493,13 +494,13 @@ class Session(object):
         the context of this session's transaction.  Otherwise, the
         connection is returned by the ``contextual_connect()`` method
         on the engine.
-        
-        the "mapper" argument is a class or mapper to which a bound engine
+
+        The `mapper` argument is a class or mapper to which a bound engine
         will be located; use this when the Session itself is either bound
         to multiple engines or connections, or is not bound to any connectable.
-        
+
         \**kwargs are additional arguments which will be passed to get_bind().
-        See the get_bind() method for details.  Note that the "ShardedSession"
+        See the get_bind() method for details.  Note that the ``ShardedSession``
         subclass takes a different get_bind() argument signature.
         """
 
@@ -510,7 +511,7 @@ class Session(object):
             return self.transaction.get_or_add(engine)
         else:
             return engine.contextual_connect(**kwargs)
-        
+
     def execute(self, clause, params=None, mapper=None, **kwargs):
         """Using the given mapper to identify the appropriate ``Engine``
         or ``Connection`` to be used for statement execution, execute the
@@ -524,24 +525,24 @@ class Session(object):
         """
 
         engine = self.get_bind(mapper, clause=clause, **kwargs)
-        
+
         return self.__connection(engine, close_with_result=True).execute(clause, params or {})
 
     def scalar(self, clause, params=None, mapper=None, **kwargs):
         """Like execute() but return a scalar result."""
 
         engine = self.get_bind(mapper, clause=clause)
-        
+
         return self.__connection(engine, close_with_result=True).scalar(clause, params or {}, **kwargs)
 
     def close(self):
-        """Close this Session.  
-        
+        """Close this Session.
+
         This clears all items and ends any transaction in progress.
-        
+
         If this session were created with ``transactional=True``, a
         new transaction is immediately begun.  Note that this new
-        transaction does not use any connection resources until they 
+        transaction does not use any connection resources until they
         are first needed.
         """
 
@@ -551,14 +552,14 @@ class Session(object):
         if self.transactional:
             # note this doesnt use any connection resources
             self.begin()
-    
+
     def close_all(cls):
         """Close *all* sessions in memory."""
-        
+
         for sess in _sessions.values():
             sess.close()
     close_all = classmethod(close_all)
-    
+
     def clear(self):
         """Remove all object instances from this ``Session``.
 
@@ -572,14 +573,14 @@ class Session(object):
         self.identity_map = self.uow.identity_map
 
     # TODO: need much more test coverage for bind_mapper() and similar !
-    
+
     def bind_mapper(self, mapper, bind, entity_name=None):
         """Bind the given `mapper` or `class` to the given ``Engine`` or ``Connection``.
 
         All subsequent operations involving this ``Mapper`` will use the
         given `bind`.
         """
-        
+
         if isinstance(mapper, type):
             mapper = _class_mapper(mapper, entity_name=entity_name)
 
@@ -597,28 +598,28 @@ class Session(object):
         self.__binds[table] = bind
 
     def get_bind(self, mapper, clause=None, **kwargs):
-        """return an engine corresponding to the given arguments.
-        
-            mapper
-                mapper relative to the desired operation
-            
-            clause
-                a ClauseElement which is to be executed.  if
-                mapper is not present, this may be used to locate
-                Table objects, which are then associated with mappers
-                which have associated binds.
-                
-            \**kwargs
-                Subclasses (i.e. ShardedSession) may add additional arguments 
-                to get_bind() which are passed through here.
+        """Return an engine corresponding to the given arguments.
+
+        mapper
+            mapper relative to the desired operation
+
+        clause
+            a ClauseElement which is to be executed.  if
+            mapper is not present, this may be used to locate
+            Table objects, which are then associated with mappers
+            which have associated binds.
+
+        \**kwargs
+            Subclasses (i.e. ShardedSession) may add additional arguments
+            to get_bind() which are passed through here.
         """
-        
+
         if mapper is None and clause is None:
             if self.bind is not None:
                 return self.bind
             else:
                 raise exceptions.InvalidRequestError("This session is unbound to any Engine or Connection; specify a mapper to get_bind()")
-                
+
         elif len(self.__binds):
             if mapper is not None:
                 if isinstance(mapper, type):
@@ -631,7 +632,7 @@ class Session(object):
                 for t in clause._table_iterator():
                     if t in self.__binds:
                         return self.__binds[t]
-                        
+
         if self.bind is not None:
             return self.bind
         elif mapper is None:
@@ -650,14 +651,14 @@ class Session(object):
         """Return a new ``Query`` object corresponding to this ``Session`` and
         the mapper, or the classes' primary mapper.
         """
-        
+
         entity_name = kwargs.pop('entity_name', None)
-        
+
         if isinstance(mapper_or_class, type):
             q = self._query_cls(_class_mapper(mapper_or_class, entity_name=entity_name), self, **kwargs)
         else:
             q = self._query_cls(mapper_or_class, self, **kwargs)
-            
+
         for ent in addtl_entities:
             q = q.add_entity(ent)
         return q
@@ -721,53 +722,53 @@ class Session(object):
 
     def refresh(self, instance, attribute_names=None):
         """Refresh the attributes on the given instance.
-        
+
         When called, a query will be issued
         to the database which will refresh all attributes with their
-        current value.  
-        
-        Lazy-loaded relational attributes will remain lazily loaded, so that 
+        current value.
+
+        Lazy-loaded relational attributes will remain lazily loaded, so that
         the instance-wide refresh operation will be followed
         immediately by the lazy load of that attribute.
-        
+
         Eagerly-loaded relational attributes will eagerly load within the
         single refresh operation.
-        
+
         The ``attribute_names`` argument is an iterable collection
-        of attribute names indicating a subset of attributes to be 
+        of attribute names indicating a subset of attributes to be
         refreshed.
         """
 
         self._validate_persistent(instance)
-            
+
         if self.query(instance.__class__)._get(instance._instance_key, refresh_instance=instance._state, only_load_props=attribute_names) is None:
             raise exceptions.InvalidRequestError("Could not refresh instance '%s'" % mapperutil.instance_str(instance))
 
     def expire(self, instance, attribute_names=None):
         """Expire the attributes on the given instance.
-        
+
         The instance's attributes are instrumented such that
         when an attribute is next accessed, a query will be issued
         to the database which will refresh all attributes with their
-        current value.  
-        
-        Lazy-loaded relational attributes will remain lazily loaded, so that 
+        current value.
+
+        Lazy-loaded relational attributes will remain lazily loaded, so that
         triggering one will incur the instance-wide refresh operation, followed
         immediately by the lazy load of that attribute.
-        
+
         Eagerly-loaded relational attributes will eagerly load within the
         single refresh operation.
-        
+
         The ``attribute_names`` argument is an iterable collection
-        of attribute names indicating a subset of attributes to be 
+        of attribute names indicating a subset of attributes to be
         expired.
         """
-        
+
         if attribute_names:
             self._validate_persistent(instance)
             _expire_state(instance._state, attribute_names=attribute_names)
         else:
-            # pre-fetch the full cascade since the expire is going to 
+            # pre-fetch the full cascade since the expire is going to
             # remove associations
             cascaded = list(_cascade_iterator('refresh-expire', instance))
             self._validate_persistent(instance)
@@ -777,11 +778,11 @@ class Session(object):
                 _expire_state(c._state, None)
 
     def prune(self):
-        """Removes unreferenced instances cached in the identity map.
+        """Remove unreferenced instances cached in the identity map.
 
         Note that this method is only meaningful if "weak_identity_map"
         is set to False.
-        
+
         Removes any object in this Session's identity map that is not
         referenced in user code, modified, new or scheduled for deletion.
         Returns the number of objects pruned.
@@ -819,7 +820,7 @@ class Session(object):
         """Bring the given detached (saved) instance into this
         ``Session``.
 
-        If there is a persistent instance with the same instance key, but 
+        If there is a persistent instance with the same instance key, but
         different identity already associated with this ``Session``, an
         InvalidRequestError exception is thrown.
 
@@ -840,7 +841,7 @@ class Session(object):
 
         self._save_or_update_impl(instance, entity_name=entity_name)
         self._cascade_save_or_update(instance)
-    
+
     def _cascade_save_or_update(self, instance):
         for obj, mapper in _cascade_iterator('save-update', instance, halt_on=lambda c:c in self):
             self._save_or_update_impl(obj, mapper.entity_name)
@@ -878,7 +879,7 @@ class Session(object):
             mapper = _object_mapper(instance)
         if instance in _recursive:
             return _recursive[instance]
-        
+
         key = getattr(instance, '_instance_key', None)
         if key is None:
             merged = attributes.new_instance(mapper.class_)
@@ -888,7 +889,7 @@ class Session(object):
             elif dont_load:
                 if instance._state.modified:
                     raise exceptions.InvalidRequestError("merge() with dont_load=True option does not support objects marked as 'dirty'.  flush() all changes on mapped instances before merging with dont_load=True.")
-                    
+
                 merged = attributes.new_instance(mapper.class_)
                 merged._instance_key = key
                 merged._entity_name = entity_name
@@ -905,14 +906,14 @@ class Session(object):
         elif dont_load:
             merged._state.commit_all()
         return merged
-            
+
     def identity_key(cls, *args, **kwargs):
         """Get an identity key.
 
         Valid call signatures:
 
         * ``identity_key(class, ident, entity_name=None)``
-        
+
           class
               mapped class (must be a positional argument)
 
@@ -923,12 +924,12 @@ class Session(object):
               optional entity name
 
         * ``identity_key(instance=instance)``
-        
+
           instance
               object instance (must be given as a keyword arg)
 
         * ``identity_key(class, row=row, entity_name=None)``
-        
+
           class
               mapped class (must be a positional argument)
 
@@ -969,13 +970,13 @@ class Session(object):
         mapper = _object_mapper(instance)
         return mapper.identity_key_from_instance(instance)
     identity_key = classmethod(identity_key)
-    
+
     def object_session(cls, instance):
-        """return the ``Session`` to which the given object belongs."""
-        
+        """Return the ``Session`` to which the given object belongs."""
+
         return object_session(instance)
     object_session = classmethod(object_session)
-    
+
     def _save_impl(self, instance, **kwargs):
         if hasattr(instance, '_instance_key'):
             raise exceptions.InvalidRequestError("Instance '%s' is already persistent" % mapperutil.instance_str(instance))
@@ -1027,7 +1028,7 @@ class Session(object):
             if key is not None:
                 self.identity_map[key] = instance
             instance._sa_session_id = self.hash_key
-        
+
     def _unattach(self, instance):
         if instance._sa_session_id == self.hash_key:
             del instance._sa_session_id
@@ -1036,37 +1037,37 @@ class Session(object):
         """Validate that the given instance is persistent within this
         ``Session``.
         """
-        
+
         return instance in self
 
     def __contains__(self, instance):
-        """return True if the given instance is associated with this session.
-        
+        """Return True if the given instance is associated with this session.
+
         The instance may be pending or persistent within the Session for a
         result of True.
         """
-        
+
         return instance._state in self.uow.new or (hasattr(instance, '_instance_key') and self.identity_map.get(instance._instance_key) is instance)
 
     def __iter__(self):
-        """return an iterator of all instances which are pending or persistent within this Session."""
-        
+        """Return an iterator of all instances which are pending or persistent within this Session."""
+
         return iter(list(self.uow.new.values()) + self.uow.identity_map.values())
 
     def is_modified(self, instance, include_collections=True, passive=False):
-        """return True if the given instance has modified attributes.
-        
+        """Return True if the given instance has modified attributes.
+
         This method retrieves a history instance for each instrumented attribute
         on the instance and performs a comparison of the current value to its
         previously committed value.  Note that instances present in the 'dirty'
         collection may result in a value of ``False`` when tested with this method.
-        
-        'include_collections' indicates if multivalued collections should be included
+
+        `include_collections` indicates if multivalued collections should be included
         in the operation.  Setting this to False is a way to detect only local-column
         based properties (i.e. scalar columns or many-to-one foreign keys) that would
         result in an UPDATE for this instance upon flush.
-        
-        the 'passive' flag indicates if unloaded attributes and collections should
+
+        The `passive` flag indicates if unloaded attributes and collections should
         not be loaded in the course of performing this test.
         """
 
@@ -1077,17 +1078,17 @@ class Session(object):
             if added or deleted:
                 return True
         return False
-        
+
     dirty = property(lambda s:s.uow.locate_dirty(),
-                     doc="""A ``Set`` of all instances marked as 'dirty' within this ``Session``.  
-                     
+                     doc="""A ``Set`` of all instances marked as 'dirty' within this ``Session``.
+
                      Note that the 'dirty' state here is 'optimistic'; most attribute-setting or collection
                      modification operations will mark an instance as 'dirty' and place it in this set,
-                     even if there is no net change to the attribute's value.  At flush time, the value 
+                     even if there is no net change to the attribute's value.  At flush time, the value
                      of each attribute is compared to its previously saved value,
                      and if there's no net change, no SQL operation will occur (this is a more expensive
                      operation so it's only done at flush time).
-                     
+
                      To check if an instance has actionable net changes to its attributes, use the
                      is_modified() method.
                      """)
@@ -1099,23 +1100,23 @@ class Session(object):
                    doc="A ``Set`` of all instances marked as 'new' within this ``Session``.")
 
 def _expire_state(state, attribute_names):
-    """standalone expire instance function. 
-    
-    installs a callable with the given instance's _state
+    """Standalone expire instance function.
+
+    Installs a callable with the given instance's _state
     which will fire off when any of the named attributes are accessed;
     their existing value is removed.
-    
+
     If the list is None or blank, the entire instance is expired.
     """
-    
+
     if state.trigger is None:
         def load_attributes(instance, attribute_names):
             if object_session(instance).query(instance.__class__)._get(instance._instance_key, refresh_instance=instance._state, only_load_props=attribute_names) is None:
                 raise exceptions.InvalidRequestError("Could not refresh instance '%s'" % mapperutil.instance_str(instance))
         state.trigger = load_attributes
-        
+
     state.expire_attributes(attribute_names)
-    
+
 register_attribute = unitofwork.register_attribute
 
 _sessions = weakref.WeakValueDictionary()
@@ -1138,4 +1139,4 @@ def object_session(instance):
 # Lazy initialization to avoid circular imports
 unitofwork.object_session = object_session
 from sqlalchemy.orm import mapper
-mapper._expire_state = _expire_state
\ No newline at end of file
+mapper._expire_state = _expire_state