don't use 'from' (was Re: module variable scope)

Alex Martelli aleax at aleax.it
Tue Oct 28 08:48:52 EST 2003


Stefan Quandt wrote:
   ...
> <begin b.py>
> from a import v, setv, getv

The from statement takes a "snapshot" at that instant of time of
the values currently bound to those names in the other module,
binding each value to the same name in the current module.

That's all.  It establishes no magical "persistent linkage
between names in different modules" -- there exists no concept
of such magical persistent linkage in Python.

Any rebinding of those or other names in the other module in
the future will be totally irrelevant to the binding of said
names in the current module.


> I expected variable v to be changed by calling setv() but it is not.
> Who can explain this?

Who can explain your expectations, I dunno.  I hope the
explanation of the behavior was clear.

My often-repeated recommendation is: forget the from statement's
very existence.  Use

import b

and refer to b.v -- NOT to bare v -- and THEN everything will work
according to expectations.

The 'from' statement is occasionally a handy shortcut if you
know what you're doing, but it doesn't work well when you're
not sure what you're doing, nor when any name rebinding or
module reloading may be involved.  That's three strikes
against it, which means _it's out_:-).

The 'import' statement has basically no counter-indications.
If a module's name is long so it gets weary writing
theothermodule.v all the time, use the 'as' clause of import:

import theothermodule as t

and happily refer to t.v -- just 2 characters longer than
barename v, AND with other advantages (immediate clarity of
where the name comes from) as well as avoiding surprises.


Alex





More information about the Python-list mailing list