views:

66

answers:

1

Hi, 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

+3  A: 

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
SilentGhost
but when I import the Main I can't run the code
Federico
@Federico: import main? what do you mean?
SilentGhost
@Federico: Please update your question with the code that doesn't work. And please be very, very clear on "can't run the code". What does that mean?
S.Lott
I mean import the Main.py which has a main
Federico
@Federico: see my edit
SilentGhost
@SilentGhost: thanks it worked.
Federico
why do I have a -3 in my question?
Federico
@Federico: you have -2 at the moment, I suppose a couple of people didn't think your question unclear or not useful. I'd think it was before you posted clarification.
SilentGhost