Addind imports to a class namespace

Peter Otten __peter__ at web.de
Sat Jul 11 02:51:48 EDT 2009


Ryan K wrote:

> In order to avoid circular imports, I have a class that I want to
> improve upon:
> 
> Class GenerateMenuXhtml(threading.Thread):
>     """
>     Subclasses a threading.Thread class to generate a menu's XHTML in
> a separate
>     thread. All Link objects that have this menu associated with it
> are gathered
>     and combined in an XHTML unordered list.
> 
>     If the sender is of type Link, then all menus associated with that
> link are
>     iterated through and rebuilt.
>     """
>     def __init__(self, instance):
>         from asqcom.apps.staticpages.models import Menu, Link
>         self.Link = Link
>         self.Menu = Menu
> 
> As you can see I just expose these imports by attaching them to
> members of the class. There must be "prettier" option though where I
> can just add these imoprts to the class's namespace so all methods of
> any instance will have access to the imported modules.
> 
> How would I go about doing this? How can I access the namespace of any
> class? Through Class.__dict__?

You can write either

class A(object):
    from some.module import Menu, Link

or 

class A(object):
    @classmethod
    do_imports(cls):
        from some.module import Menu, Link
        cls.Menu = Menu
        cls.Link = Link

A.do_imports()

to put the names into the class. The first form performs the import while 
the containing module is imported and therefore won't help with breaking 
circles. In the second form you have to defer the A.do_imports() method call 
until the import from some.module is safe.

But I still recommend that you have another look at your package 
organization to find a way to avoid circles.

Peter




More information about the Python-list mailing list