Writing to module

Lets say I have these 3 (tiny) python files -

a.py

myvar = 'a'

b.py

import a
import c

myvar = 'b'
c.pr()

c.py

from a import myvar

def pr():
    print myvar

Now if I execute b.py I get output

a

But I really want output to be as

b

So please tell me how can I restructure/modify the programs so that the module-wide myvar can be assigned a different value.


In b.py , you are setting b.py 's myvar. You want to access a's value of myvar. So b.py might look like:

import a
import c

a.myvar = 'b' # belongs to a
myvar = 'something different' # belongs to b
c.pr()

And you need to update c.py so that it uses a.py 's myvar, not it's own local copy. So c.py :

import a

def pr():
    print a.myvar

Why?

In your original c.py , when you call from a import myvar , this is equivalent to:

import a
myvar = a.myvar

This makes a local version of myvar in c.py upon import. If this is confusing, I found this article about how python variables work very informative.


I'd do it by having a fourth module d.py .

This module is imported by 'a', 'b', & 'c'.

As in the docs:

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere

Just be careful; Once you've created this config module because it was necessary, it's easy to get carried away and start adding other variables to it just because it's there. Most of the time there is a better way...

链接地址: http://www.djcxy.com/p/54802.html

上一篇: 导入如何用作用作单例模块的​​模块?

下一篇: 写入模块