Sharing package data across files

zackbaker at gmail.com zackbaker at gmail.com
Tue Jun 28 15:55:30 EDT 2016


On Tuesday, June 28, 2016 at 1:17:23 PM UTC-6, scott... at gmail.com wrote:
> I'm trying to create a package in which the constituent files share some state.  Apparently, I don't understand scopes, namespaces, and package semantics as well as I thought I did.  Here's the directory structure for a simplified example:
> 
>    example/
>      __init__.py
>      vars.py
>      funcs.py
> 
> vars.py defines a single variable:
> 
>     foo = 123
> 
> funcs.py defines a function that reads and writes that variable:
> 
>     def bar():
>         global foo
>         foo += 1
>         return foo
> 
> __init__.py exposes both of those to the caller:
> 
>     from vars import foo
>     from funcs import bar
> 
> Alas, it seems the bar function does not reside in the same global scope as the foo variable:
> 
>     >>> from example import foo, bar
>     >>> foo
>     123
>     >>> bar()
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in <module>
>       File "example/funcs.py", line 3, in bar
>         foo += 1
>     NameError: global name 'foo' is not defined
> 
> How can I make the example package work like one integrated module even though in reality it's split across multiple files?
> 
> Thanks,
> -- Scott

This problem of references is addressed in:
http://stackoverflow.com/questions/710551/import-module-or-from-module-import

>From Michael Ray Lovett: 
For example, if I do this in module a:

from foo import bar
bar = "oranges"

No code outside of a will see bar as "oranges" because my setting of bar merely affected the name "bar" inside module a, it did not "reach into" the foo module object and update its "bar".



More information about the Python-list mailing list