Just-In-Time importing

Michal Wallace sabren at manifestation.com
Tue Jun 13 22:53:17 EDT 2000


Hey all,

   I think I brought this up a few months ago, but I just now got
around to deciding on an implementation. I have a multi-file module
called "zikebase" that has various classes defined, one per file. For
example, the file, zikebase/Node.py contains a class called Node. I
wanted all of these classes to be available with a simple "import
zikebase", but I *didn't* want the overhead of importing a bunch of
files I wasn't going to need. Here's what I did:

# BEGIN ####################

dbc = my_database_connection

__objs=(
    'Content',
    'Picture',
    'User',
    'UserAuth',
    'ObjectEditor',
    'Node'
    )

for item in __objs:
    _ = "def %s(*args, **kwargs):"           "\n" \
        "    import zikebase, %s"            "\n" \
        "    zikebase.%s = %s.%s"            "\n" \
        "    return apply(%s.%s, args, kwargs)\n"
    _ = _ % ((item,) * 7)
    exec(_)


# END #####################


The nice thing about this technique is that you can 
configure or replace the classes on the fly:

>>> class Vertex():
>>>   pass
>>>
>>> import zikebase
>>> zikebase.dbc = some_other_database
>>> zikebase.Node = Vertex

Now, if zikebase.Content were usually a subclass of zikebase.Node (it
isn't), creating a zikebase.Content() would produce something that was
a subclass of Vertex instead. This can come in really handy if you
want to add something to every class in an object hierarchy and don't
want to (or can't) actually change the original top-level code. (It
sure beats subclassing every item in the tree, or writing a
wrapper-factory)


Cheers,

- Michal
------------------------------------------------------------------------
Zike Interactive    http://www.zike.net/    http://zike.sourceforge.net/
------------------------------------------------------------------------






More information about the Python-list mailing list