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
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.

🌐
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 »
Discussions

object oriented - Module with globals or Class with attributes? - Software Engineering Stack Exchange
I wanted to develop my code that is both pythonic and also consistent with what is already in place (I might be overthinking this as well). I've also stumbled upon this other related question that got no definitive answer to it. So my question is: What is the best practice in this situation. Do I keep writing code that are modules using global variables to define state (keep consistency but let pylint mad) or should I follow the road of classes ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
August 19, 2019
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
19
0
July 29, 2022
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
9
0
June 11, 2024
Global variables in python classes
#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. More on reddit.com
🌐 r/learnpython
10
0
July 10, 2024
People also ask

How do I make a global variable in Python?
To make a global variable, just define it at the top level of your script. For example, x = 10. Now you can access this x inside and outside of functions.
🌐
wscubetech.com
wscubetech.com › resources › python › global-variable
Global Variable in Python: Explained With Examples
What is a global variable in Python, and why do I need it?
A global variable in Python is one you define outside any function. You use it when you want the same variable to be accessed or shared across multiple functions in your code.
🌐
wscubetech.com
wscubetech.com › resources › python › global-variable
Global Variable in Python: Explained With Examples
What is variable scope in Python?
Variable scope is the area in which parts of a program can access the variable. In Python, there are four variable scopes:LocalGlobalEnclosingBuilt-in
🌐
wscubetech.com
wscubetech.com › resources › python › global-variable
Global Variable in Python: Explained With Examples
🌐
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.
🌐
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.
🌐
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 ...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › global-local-variables-python
Global and Local Variables in Python - GeeksforGeeks
To modify a global variable use the global keyword. ... Explanation: Inside fun(), Python assumes 's' is local since we try to modify it.
Published   2 weeks ago
🌐
Coursera
coursera.org › browse › computer science › software development
Programming for Everybody (Getting Started with Python) | Coursera
May 4, 2021 - Offered by University of Michigan. This course aims to teach everyone the basics of programming computers using Python. We cover the basics ... Enroll for free.
Rating: 4.8 ​ - ​ 233K votes
🌐
WsCube Tech
wscubetech.com › resources › python › global-variable
Global Variable in Python: Explained With Examples
February 10, 2026 - Learn about global variables in Python with examples in this tutorial. Understand how to use and manage them effectively in your Python code.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-variables
Python Variables - GeeksforGeeks
Python variables hold references to objects, not the actual objects themselves. Reassigning a variable does not affect other variables referencing the same object unless explicitly updated.
Published   2 weeks ago
🌐
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.
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
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

🌐
Quora
quora.com › How-do-you-create-a-global-variable-in-Python-3
How to create a global variable in Python 3 - Quora
Answer (1 of 2): Variable assignments at the top level of a program (outside of any class or function definition and not import into a module's namespace, are global be default. Additionally you can define (create) a global variable within a nested scope by using the global keyword (and invoking...
🌐
Programiz
programiz.com › python-programming › global-keyword
Python Global Keyword (With Examples)
In Python, the global keyword allows us to modify the variable outside of the current scope.
🌐
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.
🌐
Mrcet
mrcet.com › downloads › digital_notes › CSE › III Year › PYTHON PROGRAMMING NOTES.pdf pdf
PYTHON PROGRAMMING III YEAR/II SEM MRCET PYTHON PROGRAMMING [R17A0554]
Python to suppress its usual special meaning. It is then interpreted simply as a literal single ... Variables are nothing but reserved memory locations to store values.
🌐
Python.org
discuss.python.org › python help
How to make variables global by default, Python 3.11 - Python Help - Discussions on Python.org
June 11, 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.
🌐
PythonHello
pythonhello.com › fundamentals › python-global-variables
Python Global Variables
In Python, a global variable is a variable that is defined outside of any function or class and is available for use throughout the entire program.
🌐
scikit-learn
scikit-learn.org › stable › modules › clustering.html
2.3. Clustering — scikit-learn 1.8.0 documentation
Clustering of unlabeled data can be performed with the module sklearn.cluster. Each clustering algorithm comes in two variants: a class, that implements the fit method to learn the clusters on trai...
🌐
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.
🌐
Intellipaat
intellipaat.com › home › blog › how to use a global variable in a function in python?
How to Use a Global Variable in a Function in Python? - Intellipaat Blog
1 month ago - ... Explanation: Environment variables are accessed through os.environ, and here, ‘GLOBAL_VAR’ is defined as 18 to 25. Global variables can be defined as class variables and then accessed through the class or an instance.