eureka
eureka

Reputation: 71

Why is the use of global variables giving undefined?

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

Answers (2)

Gino Mempin
Gino Mempin

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:

  1. As mentioned in the other answer, the 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).
  2. Avoid global variables unless you really really need to. You might want to read Why are global variables evil?. Rather than ask, "how to make globals work", in this case, it seems better to think "how to refactor this without globals". If your 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.
  3. Avoid doing 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

Sven Rusch
Sven Rusch

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

Related Questions