python – Problems trying to access to a global var – Education Career Blog

I know how to use the global variables when they are defined in a class, but I have a global variable in a main.
If I want to use it inside a class, which would be the import to access it?

My main is something like this

Main.py:

from EvolutionaryAlgorithm import EvolutionaryAlgorithm
initialTimeMain = 0

if __name__ == '__main__':
    evolutionaryAlgorithm= EvolutionaryAlgorithm()
.
.

and my EvolutionaryAlgorithm class has a method which uses the initialTimeMain variable.
the problem is when I add this import in the EvolutionaryAlgorithm:

EvolutionaryAlgorithm.py

import Main 

because when I run the script, an error appears

from EvolutionaryAlgorithm import
EvolutionaryAlgorithm ImportError:
cannot import name
EvolutionaryAlgorithm

the import isn’t recognized anymore

,

You have a case of circular imports, short-term solution is to move import statement inside the if clause:

initialTimeMain = 0

if __name__ == '__main__':
    from EvolutionaryAlgorithm import EvolutionaryAlgorithm
    evolutionaryAlgorithm= EvolutionaryAlgorithm()

A better, long-term solution would be to refactor your code so that you don’t have circular imports or initialTimeMain is defined in the EvolutionaryAlgorithm.py, which of course would be available in Main.py with your existing import strategy.

Old answer:

a.py:

globalvar = 1
print(globalvar)             # prints 1
if __name__ == '__main__':
    print(globalvar)         # prints 1

b.py:

import a
print(a.globalvar)           # prints 1

Leave a Comment