Reputation: 71
I can't seem to work out what I'm doing wrong with my variable. Basically I have a variable in my main.py which I need to adjust in a function in my function.py. But I'm getting an error that the variable has not been defined.
What am I doing wrong?
main.py:
from function.functions import *
loaded_tables = []
do_something()
functions.py:
def do_something():
global loaded_tables
loaded_tables.append('test')
Upvotes: 0
Views: 225
Reputation: 29549
Let's try to solve the problem while at the same time avoiding some bad practices.
Here's the modified functions.py:
def do_something(params):
# computing something based on params..
return 'test'
Here's the modified main.py:
from functions import do_something
loaded_tables = []
print(loaded_tables)
result = do_something(123)
loaded_tables.append(result)
print(loaded_tables)
Running it:
$ python main.py
[]
['test']
Changes:
loaded_tables
name is scoped only to the main.py module and it's not available to functions.py. Saying global
does not tell Python to look for it in the main
module (or in other files).main
module holds the data
, and the functions
module is supposed to do some operations based on it, just pass parameters to the function (params required to "do something"), then return the result to main. All mutations on the data are then done only on the main module. This makes it more modular and is helpful when writing tests, as the function can be tested independently from loaded_tables
.import *
. Maybe this is just simplification for sample code, but still, it's better to explicitly import what you need. It can make it hard to debug and for your IDE to work its intellisense. See Why is “import *” bad?.Upvotes: 1
Reputation: 1377
Global variables in Python are not truly global, they are module-scoped. That means that you would be able to access loaded_tables
from any function in you module main
. If you want to use it in any other module, you have to import it. In your case that would give you a circular import and would thus not work properly.
As @klaus-d suggests in their comment, it is good practice to avoid global variables and simply pass parameters to the functions.
If you really would like to use global variables, you could define them in a separate module (e.g. app_globals.py
) and import them from there when you need to access them.
Upvotes: 6