Variable inside module

Ken Seehof kseehof at neuralintegrator.com
Mon Apr 14 17:14:57 EDT 2003


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

>Hi!
>
>Can someone please explain-me what is
>happening here:
>
>Given the followin bar.py 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 __init__.py:
>
>         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 bar.py file and one accessed from
>within the python interpreter. What is going on
>here?
>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
module.

- Ken Seehof
www.neuralintegrator.com
kseehof @ neuralintegrator.com







More information about the Python-list mailing list