Variable inside module

Ken Seehof kseehof at
Mon Apr 14 23:14:57 CEST 2003

At 01:08 PM 4/14/2003 Monday, Marcelo A. Camelo wrote:

>Can someone please explain-me what is
>happening here:
>Given the followin file (placed
>inside a foo/ directory):
>         var = 'foo'

Adds 'var':'foo' into the module bar namespace

>         def SetVar():
>             global var
>             var = 'bar'
>         def PrintVar():
>             global var
>             print 'var:', var
>In the same foo/ directory, I've placed
>the following
>         from bar import *

Copies 'var':'foo' from module bar into the foo namespace.

>Then, in the interactive python interpreter:
>         >>> import foo
>         >>> print foo.var
>         foo
>         >>> foo.PrintVar()
>         var: foo
>         >>> foo.SetVar()

Sets 'var':'bar' in the global namespace.

>         >>> foo.PrintVar()
>         var: bar

Prints 'var':'bar' in the global namespace.

>         >>> print foo.var
>         foo

Prints 'var':'foo' in the foo namespace.

>         >>>
>What I don't understand is that foo.var seems
>to be two different variables: one accessed
>inside the file and one accessed from
>within the python interpreter. What is going on
>Thank you,
>Marcelo A. Camelo

Not exactly.  It's just that the foo module is not
the same as the global namespace.

The statement "var = 'foo'" is executed in the
bar module, then the value is copied into the foo

- Ken Seehof
kseehof @

More information about the Python-list mailing list