Odd behaviour on importing variable from module

Peter Otten __peter__ at web.de
Sat Aug 23 08:37:10 EDT 2008


rs387 wrote:

> I've found the following behaviour on importing a variable from a
> module somewhat odd. The behaviour is identical in Python 2.5 and
> 3.0b2.
> 
> In summary, here's what happens. I have a module, oddmodule.py
> (below), that defines a variable, OddVariable, by assigning a value A
> to it. The file I execute, mainfile.py, imports and re-binds
> OddVariable to a value B. I have two test modules which import the
> OddVariable in two different ways, one via "import oddmodule" and
> another via "from oddmodule import OddVariable".
> 
> The weird behaviour is that by importing using the former syntax, I
> can see OddVariable bound to B (as expected), but the latter syntax
> sees it bound A.
> 
> Is this the intended behaviour? 

Yes. Think of

from module import var

as a shortcut for

import module
var = module.var
del module

This is not entirely correct as 'from package import module' implicitly
imports 'module' but should explain the binding behaviour.

Peter



More information about the Python-list mailing list