Why do directly imported variables behave differently than those attached to imported module?

Terry Reedy tjreedy at udel.edu
Tue May 3 13:13:12 EDT 2011


Your problem is reveal in the subject line. As discussed in many other 
threads, including a current one, Python does not have 'variables' in 
the way that many understand the term. Python binds names to objects.
Binding statements (assignment, augmented assignment, import, def, 
class, and others with 'as' clauses) all bind names to objects.

Suppose we both have address books. You copy all entries from my book to 
yours. Afterwards, I update an entry in my book. That does not change 
the now obsolete entry in your book.

On 5/3/2011 12:31 PM, Dun Peal wrote:
>      # module foo.py
>      var = 0
>
>      def set():
>          global var
>          var = 1

Module foo's dict now has two entries for 'var' and 'set' bound to int 0 
and a function. Note that 'set' is a builtin class name so not the best 
choice.
>
> Script using this module:

Script creates module '__main__'

>      import foo

This binds 'foo' to module foo in __main_'s dict.

>      from foo import *

This copies foo's dict to __main__'s dict.

>      print var, foo.var
>      set()

This changes foo's dict, rebinding 'var' to int 1. It does not change 
__main__'s dict. How could it? In the same way, 'var = 2' would leave 
foo's dict unchanged. __main__.var.

>      print var, foo.var
>
> Script output:
>
>      0 0
>      0 1

If instead of 'from foo import *', you had written 'from foo import var 
as rav', then perhaps you would not have been so surprised that 
__main__.rav and foo.var have independent fates.

You have discovered that using from x import * is a bad idea when module 
x has global names that get rebound.

-- 
Terry Jan Reedy




More information about the Python-list mailing list