I have stored some data in another module that I want to call, but can't retrieve the variable values from that module. How would I do this?
module_with_data.py:
def values():
global x
x = 1
values()
main.py:
import module_with_data
x = 1 + x
What it should output is 2 but I can't get this work.
2 Answers 2
module_with_data.py
x = 1
main.py
from module_with_data import x
x = x + 1
print(x)
Looks like you wanted a clean syntax like this, however, do be careful with using naked variables from modules as if they were global, especially when you are changing their value. For simple code, it is fine, but we would forget things once the code base grows large.
1 Comment
import module_with_data as mwd and use mwd.x to avoid that issueThe x you are changing doesn't exist until it is assigned a value, but since it is assigned a value inside a function, it is created in scope of that function and won't be available outside it.
You can assign a global x a value inside a function, if that makes more sense in your case, but you have to declare x as global:
def values()
global x
x = 1
values()
Alternatively, don't declare it in a function, but just put the assignments in the main body of the module:
x = 1
Secondly, you're importing the entire module, but that means you only have access to its contents if you namespace them:
import module_with_data
module_with_data.x = 1 + module_with_data.x
Or, you can add it to the namespace of the script importing it:
from module_with_data import x
x = 1 + x
xis not in the module scope ofmodule_with_databecause you've wrapped it in the scope of a pointless function.import module_with_dataintroduces exactly one name to your current namespace:module_with_data. You have to be explicit about referring to names in the imported module:module_with_data.x, perhaps, although that won't work either as there is no such thing asxin the module (it's a local variable instead).global x, inmodule_with_data.pyyou would need to do afrom module_with_data import xto bring the variable into the scope of code inmain.py. Alternatively you could reference it this way:module_with_data.x = module_with_data.x + 1.values()in the module. That's why importing the module doesn't make it visible.