Remmerton
Remmerton

Reputation: 35

How to import a variable defined in a module?

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.

Upvotes: 0

Views: 1637

Answers (2)

Grismar
Grismar

Reputation: 31396

The 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

Upvotes: 1

Indominus
Indominus

Reputation: 1258

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.

Upvotes: 1

Related Questions