简体   繁体   中英

How to edit global variable in module?

I am writing a Python module and I have a function that defines a new variable in the module. I want to set a variable that can be accessed in the file that is importing the file. If that is confusing, here is my code:

# main.py

import other_module

other_module.set_variable("var1")

print(other_module.var1) # This is not a NameError

print(var1) # NameError

However, if I do something slightly different:

# main.py

from other_module import *

set_variable("var1")

print(var1) # NameError

print(other_module.var1) # NameError

And other_module.py :

#     other_module.py

def set_variable(name):
    exec("""
global %s
%s = 5
         """ % (name, name))

I have no control over main.py . That is thr consumer's code. I want to be able to access and change main.py 's globals. I want this to work:

# main.py

from other_module import *

set_variable("var")

print(var) # This should print 5

What you are doing sounds like class method behavior to me. A class will be safer to use than the global namespace, try a class?

This works:

# other.py
class Other(object):

    @classmethod
    def set_variable(cls, name):
        exec('Other.%s = 5' % name)

# main.py
from other import Other

Other.set_variable('x')
print Other.x

# output
% ./main.py
5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM