How to declare a global variable from within a class?

You should really rethink whether or not this is really necessary, it seems like a strange way to structure your program and you should phihag's method which is more correct.

If you decide you still want to do this, here is how you can:

>>> class myclass(object):
...     global myvar
...     myvar = 'something'
...
>>> myvar
'something'

You can do like

# I don't like this hackish way :-S
# Want to declare hackish_global_var = 'something' as global
global_var = globals()
global_var['hackish_global_var'] = 'something'

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:
    pass

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)

Tags:

Python

Class