Python Forum
Import and variable level - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Import and variable level (/thread-16830.html)



Import and variable level - tazalapizza - Mar-16-2019

Hi, I am working with a few friends on a project where everyone makes some functions that have to use the same variables, for example x here. Every function will be imported in a main.py file and then use x, which is created in main.py. We thought that it would not be necessary to put x as an argument of every function because x would be a global variable, but it seems like it is not. Is there a solution to make this work, other than storing every variables in a file and importing this file everywhere ? Or is there a cleaner way to use our functions together ? We would like to avoid putting the variables as arguments of the functions because there is a lot of them.
Example:
#secondary.py
def function():
    print("secondary:", x)


#main.py
from secondary import function
x=0
function()
I get
Error:
NameError: name 'x' is not defined
and I want to print "secondary: 0"


RE: Import and variable level - Larz60+ - Mar-16-2019

you need to pass x as an argument:
#secondary.py
def function(x):
    print("secondary:", x)
 
 
#main.py
from secondary import function
x=0
function(x)
Also, be aware that you set x to 0 prior to running function