Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

python - accessing "module scope" vars

I'm currently learning Python, and I have to work on a Python 2.7 project.

Accessing "module scope" variables in functions of the module itself is a bit confusing for me, and I didn't succeed in finding a satisfying way.

My attempts so far:

Way 1:

my_module.py

my_global_var = None

def my_func():
    global my_global_var
    my_global_var = 'something_else'

Here I think that confusing local and "module scope" vars may be quite easy.

Way 2:

my_module.py

import my_module

my_global_var = None

def my_func():
    my_module.my_global_var = 'something_else'

Here, the name of "my_module" could not be as easily changed as "way 1" when necessary. Plus, importing a module into itself sounds quite weird.

What would you recommend? Or would you suggest something else? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You probably want to read up on Python's namespaces. Way 1 is correct but generally unnecessary, never use 2. An easier approach is to just use a dict (or class or some other object):

my_globals = {'var': None}

def my_func():
    my_globals['var'] = 'something else'

Assignments always go into the innermost scope and the innermost scope is always searched first, thus the need for the global keyword. In this case you aren't assigning to a name, so it's unnecessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...