How to bind engine when I want, when using declarative_base in SQLAlchemy?
Question: Here's my code:

    
    
    from sqlalchemy import create_engine, Column, Integer
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    
    database_url = 'mysql://some_path'
    engine = create_engine(database_url)
    Base = declarative_base(engine)
    
    class Users(Base):
        __tablename__ = 'Users'
        __table_args__ = {'autoload':True}
    
    metadata = Base.metadata
    Session = sessionmaker(bind=engine)
    session = Session()
    

It works, but...  
**Is it possible to bind engine when I want, not only at import time?** So I
can wrap this implementation into class.

For now, I get

    
    
        class Users(Base):
      File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.6.5-py2.5.egg/sqlalchemy/ext/declarative.py", line 1231, in __init__
        _as_declarative(cls, classname, cls.__dict__)
      File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.6.5-py2.5.egg/sqlalchemy/ext/declarative.py", line 1122, in _as_declarative
        **table_kw)
      File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.6.5-py2.5.egg/sqlalchemy/schema.py", line 209, in __new__
        table._init(name, metadata, *args, **kw)
      File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.6.5-py2.5.egg/sqlalchemy/schema.py", line 260, in _init
        msg="No engine is bound to this Table's MetaData. "
      File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.6.5-py2.5.egg/sqlalchemy/schema.py", line 2598, in _bind_or_error
        raise exc.UnboundExecutionError(msg)
    sqlalchemy.exc.UnboundExecutionError: No engine is bound to this Table's MetaData. Pass an engine to the Table via autoload_with=<someengine>, or associate the MetaData with an engine via metadata.bind=<someengine>
    

when engine is not specified: `Base = declarative_base()`


Answer: At least with SQLAlchemy 0.9 you can defer the binding by using
DeferredReflection. See the example in the [Using Reflection with Declarative
section of the
manual](http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/declarative.html#using-
reflection-with-declarative).

There, you can find the following example (simplified):

    
    
    from sqlalchemy.ext.declarative import declarative_base, DeferredReflection
    
    Base = declarative_base(cls=DeferredReflection)
    
    class Foo(Base):
        __tablename__ = 'foo'
        bars = relationship("Bar")
    
    class Bar(Base):
        __tablename__ = 'bar'
    
    Base.prepare(e)
    

e is the engine.

