Python – How to declare a global variable from within a class


I'm trying to declare a global variable from within a class like so:

class myclass:
    global myvar = 'something'

I need it to be accessed outside the class, but I don't want to have to declare it outside the class file. My question is, is this possible? If so, what is the syntax?

Best Solution

In your question, you specify "outside the main file". If you didn't mean "outside the class", then this will work to define a module-level variable:

myvar = 'something'

class myclass:

Then you can do, assuming the class and variable definitions are in a module called mymodule:

import mymodule

myinstance = myclass()
print mymodule.myvar 

Also, in response to your comment on @phihag's answer, you can access myvar unqualified like so:

from mymodule import myvar

print myvar

If you want to just access it shorthand from another file while still defining it in the class:

class myclass:
    myvar = 'something'

then, in the file where you need to access it, assign a reference in the local namespace:

myvar = myclass.myvar

print myvar