Best practices with import?

Gordon McMillan gmcm at
Tue Jul 31 20:04:17 CEST 2001

Jay O'Connor wrote:

[using import inside functions, classes...]

> class MyEngine:
>      def __init__ (self):
>           import engine_support
>      def doSomething (self):
>           #is engine_support is scope?
>           engine_support.do_something()


> hmmmm...I just tested it, both  references to engine_support outside of
> __init__ fail with a NameError.  *THAT* would be something useful to
> have...a class level import; import the module in __init__, it's in
> scope for the whole class
> The best workaround for now I could think of is either to assign an
> instance variable to the module


> or to assign it to a global in the module so that once it's imported,
> it's available to the whole module.
> I can see the use for being able to import a module into a function, but
> having it in visible outside of that function (especially in classes)

Assigning to an instance variable is a perfectly sane way to do that.

Note that in

def f1():
  import x
def f2()
  import x

all the heavy lifting is done when f1 executes. When f2 executes, import
finds x already in sys.modules, so the second import is very cheap (but
not free).

I would suggest staying away from trying to make a delayed import
visible globally, it's just too fragile.

- Gordon

More information about the Python-list mailing list