> class X(SQLObject):
>   _fromDatabase= True
>
> When I import this class, it has to connect to the database. 
> This is undesirable for me.  What can I do to have it connect
> lazily?  One thing I was imagining was declaring the class in
> a function and sticking it into the module dictionary.  I'm
> not so crazy about that.

Here's what I did:

import sqlobject
import new

# nasty.

def makeSQLObjectClass(connection, className, tableName, **kwargs):
    classVars = {
        '_connection'  : connection,
        '_fromDatabase': True,
        '_table'       : tableName,
        '_cacheValues' : False
    }
    classVars.update(kwargs)
    klass = new.classobj(className,(sqlobject.SQLObject,),classVars)
    return klass

Then I used a modified dependency injection recipe, derived from http://onestepback.org/cgi-bin/osbwiki.pl?DependencyInjectionCode/DepInjRb and http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413268 .

It makes sort of memoizing objects: each object holds a function, and, when asked for its 'value', calls the function the first time, saves its return value, and returns that forevermore. These are asked for their 'value' by the __getattr__ method of a DI container object

I went to all this trouble so that I could define my database in straight SQL and use _fromDatabase for everything, so I would not have to repeat the database definition in Python. It's not pretty but it takes all of the construction of the class away from the place where it's used.

>
> The only reason I'm declaring this class X at all is that
> another class, Y, let's say, has a foreign key pointing to it.