By declaring it global inside the function that accesses it:

g_c = 0

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print(g_c)

The Python documentation says this, about the global statement:

The global statement is a declaration which holds for the entire current code block.

Answer from unwind on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_variables_global.asp
Python - Global Variables
Global variables can be used by everyone, both inside of functions and outside. Create a variable outside of a function, and use it inside the function · x = "awesome" def myfunc(): print("Python is " + x) myfunc() Try it Yourself »
Top answer
1 of 7
156

By declaring it global inside the function that accesses it:

g_c = 0

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print(g_c)

The Python documentation says this, about the global statement:

The global statement is a declaration which holds for the entire current code block.

2 of 7
26

You need to move the global declaration inside your function:

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print(g_c)

The statement tells the Python compiler that any assignments (and other binding actions) to that name are to alter the value in the global namespace; the default is to put any name that is being assigned to anywhere in a function, in the local namespace. The statement only applies to the current scope.

Since you are never assigning to g_c in the class body, putting the statement there has no effect. The global statement only ever applies to the scope it is used in, never to any nested scopes. See the global statement documentation, which opens with:

The global statement is a declaration which holds for the entire current code block.

Nested functions and classes are not part of the current code block.

I'll insert the obligatory warning against using globals to share changing state here: don't do it, this makes it harder to reason about the state of your code, harder to test, harder to refactor, etc. If you must share a changing singleton state (one value in the whole program) then at least use a class attribute:

class TestClass():
    g_c = 0

    def run(self):
        for i in range(10):
            TestClass.g_c = 1
            print(TestClass.g_c)  # or print(self.g_c)

t = TestClass()
t.run()

print(TestClass.g_c)

Note how we can still access the same value from the outside, namespaced to the TestClass namespace.

Discussions

How to make variables global by default, Python 3.11
I have Python 3.11 on Windows 10 Pro. I’m still a bit new to Python but I’m learning. In Python 3.11 the variables declared in the main program are not global by default and I cannot use them in functions. So if I want to use them in a function I have to use the global prefix/keyword. More on discuss.python.org
🌐 discuss.python.org
0
June 10, 2024
design - What are the considerations between a class variable and a global variable - Software Engineering Stack Exchange
If one has the right visibility, one can access a global variable or a class variable from anywhere in the program; There is only one, shared copy of them. So why would a software engineer choose one over the other? Considerations could assume a language like Python, with no private variables, ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
September 21, 2022
Global variable Python classes - Stack Overflow
What is the proper way to define a global variable that has class scope in python? Coming from a C/C++/Java background I assume that this is correct: class Shape: lolwut = None def __in... More on stackoverflow.com
🌐 stackoverflow.com
Painful details of variable scope mixed with classes
I’m revisiting variable scope technicalities in Python for my personal interpreter project. Some time ago, I asked about that and got the tip that CPython has a multi-pass system that figures out variables, scopes, and bindings ahead of generating byte code. More on discuss.python.org
🌐 discuss.python.org
0
July 29, 2022
🌐
Reddit
reddit.com › r/learnpython › global variables in python classes
r/learnpython on Reddit: Global variables in python classes
July 10, 2024 -

Hey this question have a few sub-questions:
#1 Why this code returns name 'y' is not defined is it possible to add something like global or public tag to variables in python?

class Test:
    y = 1
    def __init__(self):
        self.__x = 1
    def print_me(self):
        print(y)
t = Test()
t.print_me()

#2 Why this code returns paradoxical response Test2.test() takes 0 positional arguments but 1 was given?

class Test2:
    def test():
        u = 5
t2 = Test2()
t2.test()

#3 Why class methods can define class variables in python?

Top answer
1 of 3
3
#1 Why this code returns name 'y' is not defined Because y is not defined in the enclosing scope. The "enclosing scope" for the line print(y) is the print_me() method. is it possible to add something like global or public tag to variables in python? Yes, you can tell Python that you want to use y from the Test() class scope like this: class Test: y = 1 def __init__(self): self.__x = 1 def print_me(self): print(Test.y) t = Test() t.print_me() #2 Why this code returns paradoxical response Test2.test() takes 0 positional arguments but 1 was given? Because the method test() is passed the instance object, but the self parameter is missing. In other words, Test2.test() is written with 0 positional arguments, but calling t2.test() automatically passes t2 as the self argument (t2 is the "1 [argument that] was given`). #3 Why class methods can define class variables in python? Class methods do not "define" class variables. Class methods can "access" class variables, using the cls parameter to represent the class object.
2 of 3
2
For 1. when you access a free variable (i.e. one that's not a parameter to the function, or defined inside the function) then Python looks for that variable in the enclosing scopes. In Python this order goes, roughly: local -> non-local (outer enclosing function) -> non-local (next outer function) etc -> globals -> built-ins, skipping over the classes entirely. This is simply a language design question, and you need to access class and instance attributes through self in Python. For 2. When you call a method then Python calls the classes function passing the object as the self argument. So if Foo is the class, then foo.bar() is the same as Foo.bar(foo). So your code t2.test() is actually going Test2.test(t2) so you get the error. You can make these so-called "static" methods with the @staticmethod decorator. If you put @staticmethod on the line before the def test(): then your code will work, as a staticmethod disables this implicit passing of self. Although, in Python (unlike in say, Java), you can just put functions outside the class and so static methods are less common. For 3. I'm not really sure what the question is... But, Python basically has no restrictions on "who" can assign attributes. So anyone can put an attribute on an object from anywhere in the code if it has a reference to that object.
🌐
Real Python
realpython.com › python-use-global-variable-in-function
Using and Creating Global Variables in Your Python Functions – Real Python
December 8, 2024 - Creating global variables inside a function is possible using the global keyword or globals(), but it’s generally not recommended. Strategies to avoid global variables include using constants, passing arguments, and employing classes and methods ...
🌐
Great Learning
mygreatlearning.com › blog › it/software development › global variables in python
Global Variables in Python
August 15, 2024 - In Python, a global variable is a variable that is defined outside of any function or class, making it accessible from anywhere within the program.
🌐
TutorialsPoint
tutorialspoint.com › how-do-i-declare-a-global-variable-in-python-class
How do I declare a global variable in Python class?
April 30, 2025 - A global variable that is declared inside the class can be accessed inside and outside the class, and it can be modified within the class using the global keyword.
🌐
GeeksforGeeks
geeksforgeeks.org › python › global-local-variables-python
Global and Local Variables in Python - GeeksforGeeks
Inside function: Python is awesome! Outside function: Python is awesome! Explanation: msg is a global variable accessible both inside and outside the display() function.
Published   September 20, 2025
Find elsewhere
🌐
Python.org
discuss.python.org › python help
How to make variables global by default, Python 3.11 - Python Help - Discussions on Python.org
June 10, 2024 - I have Python 3.11 on Windows 10 Pro. I’m still a bit new to Python but I’m learning. In Python 3.11 the variables declared in the main program are not global by default and I cannot use them in functions. So if I want to use them in a function I have to use the global prefix/keyword.
🌐
Python.org
discuss.python.org › python help
Painful details of variable scope mixed with classes - Python Help - Discussions on Python.org
July 29, 2022 - I’m revisiting variable scope technicalities in Python for my personal interpreter project. Some time ago, I asked about that and got the tip that CPython has a multi-pass system that figures out variables, scopes, and bindings ahead of generating byte code.
Top answer
1 of 2
2

There's no real difference between a package-level global (version one for you) and a class variable. They're both implementations of a situation where the state is stored in a single place.

Typically you want to avoid this for many reasons, a few including:

  • It's difficult to track who is changing state in the case that these global values are visible to the outside world.
  • It's difficult to change code later on if you need to track multiple states at once, like if you moved to a concurrent environment.
  • There's no way to get referential transparency - the behaviour of a function depends on when you call it. This makes testing very difficult, because writing solid tests means you have a way to guarantee resetting the state.

I'd recommend using an object approach with instance-level variables instead of global/class-level state:

class MyClass:
    def __init__(self):
       self._state_var = 0

    def do_something(self, arg1):
        if arg1:
            self._state_var = 1

    def say_hello(self):
        if self._state_var:
            print("Hello!")

I'd also recommend going against the current practice. The more you add to the pile of bad code, the more places there are for things to go wrong. If you build your code according to good software engineering practices, you're less likely to have issues later on.

And who knows, maybe you writing good code will encourage other people to do the same!

2 of 2
2

Globals in Python are only global to the module where they belong to, not across different modules. So the scope of STATE_VAR in both of your examples is essentially the same!

A class is required when you need (or expect to need) more than one instance of the abstraction formed by the module. If you are sure your program will not need this in the near future, a class likely does not bring you any benefit, you can stay with modules and "module globals" without any significant drawback.

For more details on when or when not to use classes in Python, see also:

  • When should I be using classes in Python.

  • Classes vs. modules in Python

🌐
Simplilearn
simplilearn.com › home › resources › software development › python global variables | definition, scope and examples
Python Global Variables | Definition, Scope and Examples
September 9, 2025 - Python global variables explained! Learn how to declare, modify and use them effectively while understanding their scope, limitations and best practices.
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.3 documentation
It is important to realize that scopes are determined textually: the global scope of a function defined in a module is that module’s namespace, no matter from where or by what alias the function is called. On the other hand, the actual search for names is done dynamically, at run time — however, the language definition is evolving towards static name resolution, at “compile” time, so don’t rely on dynamic name resolution! (In fact, local variables are already determined statically.)
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-using-variable-outside-and-inside-the-class-and-method
Python | Using variable outside and inside the class and method - GeeksforGeeks
July 11, 2025 - Outside_class1 outside_class ... the class: The variables that are defined inside the class but outside the method can be accessed within the class(all methods included) using the instance of a class....
🌐
Reddit
reddit.com › r/learnpython › global variable vs a global variable instantiated as an instance of a class
r/learnpython on Reddit: Global variable vs a Global variable instantiated as an instance of a class
February 2, 2024 -

I apologize if my terminology is wrong, I'm still fairly new to Python. This question has been asked before but I wasn't able to comprehend the answer.

I'm having trouble understanding why using Global variables is a bad practice, but instantiating a class instance to a Global variable isn't. I understand that reading from Global variables is fine, but classes seem to be used for changing states, which means if I modify an instantiated class variable I'm essentially changing a Global.

For example:

my_variable = MyClass("Hello")

def a_function():
    MyClass.my_attribute = "World"

vs

my_variable = "Hello"

def a_function():
    Global my_variable = "World"

🌐
Dive into Python
diveintopython.org › home › learn python programming › classes in python › class variables, attributes, and properties
Class Variables and Properties in Python: Public, Private and Protected
May 3, 2024 - Global variables are defined outside of any function or class, making them accessible everywhere. To define a global variable in Python, you simply declare it outside of any function or class.
🌐
Python Forum
python-forum.io › thread-32018.html
Global variables not working
I have made some global variables. A simplified version of the program (but with the same rationale) is this: sentence_1 = "hello" sentence_2 = "hello" class MyClass: def __init__(self, parent = None)
🌐
Index.dev
index.dev › blog › how-to-set-global-variables-python
How to Set Global Variables Across Modules in Python
February 27, 2025 - The singleton pattern ensures all modules share the same global state. Avoid modifying imported modules directly. Instead, use setter functions or classes. Use a dedicated config module for shared settings and constants. Consider using environment variables for sensitive or runtime-dependent settings.
🌐
freeCodeCamp
freecodecamp.org › news › global-variable-in-python-non-local-python-variables
Global Variable in Python – Non-Local Python Variables
June 10, 2022 - In Python and most programming languages, variables declared outside a function are known as global variables. You can access such variables inside and outside of a function, as they have global scope.