If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

Answer from Levon on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_variables_global.asp
Python - Global Variables
To create a global variable inside a function, you can use the global keyword. If you use the global keyword, the variable belongs to the global scope: def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x) Try it Yourself ยป
Top answer
1 of 6
549

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

2 of 6
150

Within a Python scope, any assignment to a variable not already declared within that scope creates a new local variable unless that variable is declared earlier in the function as referring to a globally scoped variable with the keyword global.

Let's look at a modified version of your pseudocode to see what happens:

# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'

def func_A():
  # The below declaration lets the function know that we
  #  mean the global 'x' when we refer to that variable, not
  #  any local one

  global x
  x = 'A'
  return x

def func_B():
  # Here, we are somewhat mislead.  We're actually involving two different
  #  variables named 'x'.  One is local to func_B, the other is global.

  # By calling func_A(), we do two things: we're reassigning the value
  #  of the GLOBAL x as part of func_A, and then taking that same value
  #  since it's returned by func_A, and assigning it to a LOCAL variable
  #  named 'x'.     
  x = func_A() # look at this as: x_local = func_A()

  # Here, we're assigning the value of 'B' to the LOCAL x.
  x = 'B' # look at this as: x_local = 'B'

  return x # look at this as: return x_local

In fact, you could rewrite all of func_B with the variable named x_local and it would work identically.

The order matters only as far as the order in which your functions do operations that change the value of the global x. Thus in our example, order doesn't matter, since func_B calls func_A. In this example, order does matter:

def a():
  global foo
  foo = 'A'

def b():
  global foo
  foo = 'B'

b()
a()
print foo
# prints 'A' because a() was the last function to modify 'foo'.

Note that global is only required to modify global objects. You can still access them from within a function without declaring global. Thus, we have:

x = 5

def access_only():
  return x
  # This returns whatever the global value of 'x' is

def modify():
  global x
  x = 'modified'
  return x
  # This function makes the global 'x' equal to 'modified', and then returns that value

def create_locally():
  x = 'local!'
  return x
  # This function creates a new local variable named 'x', and sets it as 'local',
  #  and returns that.  The global 'x' is untouched.

Note the difference between create_locally and access_only -- access_only is accessing the global x despite not calling global, and even though create_locally doesn't use global either, it creates a local copy since it's assigning a value.

The confusion here is why you shouldn't use global variables.

๐ŸŒ
Real Python
realpython.com โ€บ python-use-global-variable-in-function
Using and Creating Global Variables in Your Python Functions โ€“ Real Python
December 8, 2024 - Python handles name conflicts by searching scopes from local to built-in, potentially causing name shadowing challenges. Creating global variables inside a function is possible using the global keyword or globals(), but itโ€™s generally not ...
Top answer
1 of 16
5288

You can use a global variable within other functions by declaring it as global within each function that assigns a value to it:

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

Since it's unclear whether globvar = 1 is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the global keyword.

See other answers if you want to share a global variable across modules.

2 of 16
932

If I'm understanding your situation correctly, what you're seeing is the result of how Python handles local (function) and global (module) namespaces.

Say you've got a module like this:

# sample.py
_my_global = 5

def func1():
    _my_global = 42

def func2():
    print _my_global

func1()
func2()

You might be expecting this to print 42, but instead, it prints 5. As has already been mentioned, if you add a 'global' declaration to func1(), then func2() will print 42.

def func1():
    global _my_global 
    _my_global = 42

What's going on here is that Python assumes that any name that is assigned to, anywhere within a function, is local to that function unless explicitly told otherwise. If it is only reading from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes (e.g. the module's global scope).

When you assign 42 to the name _my_global, therefore, Python creates a local variable that shadows the global variable of the same name. That local goes out of scope and is garbage-collected when func1() returns; meanwhile, func2() can never see anything other than the (unmodified) global name. Note that this namespace decision happens at compile time, not at runtime -- if you were to read the value of _my_global inside func1() before you assign to it, you'd get an UnboundLocalError, because Python has already decided that it must be a local variable but it has not had any value associated with it yet. But by using the 'global' statement, you tell Python that it should look elsewhere for the name instead of assigning to it locally.

(I believe that this behavior originated largely through optimization of local namespaces -- without this behavior, Python's VM would need to perform at least three name lookups each time a new name is assigned to inside a function (to ensure that the name didn't already exist at module/builtin level), which would significantly slow down a very common operation.)

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how can i update a global variable with a variable from a function?
r/learnpython on Reddit: How can I update a global variable with a variable from a function?
November 6, 2021 -

I created two variables at the beginning of a script: price1 and price2

I also have a function called get_price() that will create variables: price_a and price_b. I need these function variables to update the variables from the beginning of the script.

Here is a snippet:

price1 = 0
price2 = 0

async def get_price(url):
    LOTS_OF_CODE_HERE
    return price

async def main():
    task1 = asyncio.create_task(get_price(url1))
    task2 = asyncio.create_task(get_price(url2))
    price_a = await task1
    price_b = await task2
    print(f'price_a: {price_a}')
    print(f'price_b: {price_b}')
    price1 = price_a
    price2 = price_b

asyncio.run(main())

print(f'price1: {price1}')
print(f'price2: {price2}')

expected output:

price_a: 4000
price_b: 5000
price1: 4000
price2: 5000

actual output:

price_a: 4000
price_b: 5000
price1: 0
price2: 0

What am I doing wrong here?

๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Can't use global variables within a function - Python Help - Discussions on Python.org
November 19, 2021 - hi again guys. Today iโ€™m trying out functions, but iโ€™ve run in a small (inconsistancy?) issue. Mainly iโ€™m trying to print out global variables within a function, which works, but when I try to change the value of the โ€ฆ
๐ŸŒ
Quora
quora.com โ€บ How-do-you-change-the-value-of-a-global-variable-inside-of-a-function-in-Python
How to change the value of a global variable inside of a function in Python - Quora
Answer (1 of 3): A global variable is one that has no hidden scope โ€” its scope is everywhere. That means universal visibility. Globals are single points of dependency between all areas of your program. That is not a good idea. The mechanism (statement) to change a global is the same as for ...
Find elsewhere
๐ŸŒ
W3Resource
w3resource.com โ€บ python-interview โ€บ how-do-you-access-global-variables-inside-a-function.php
Accessing and modifying global variables in Python functions
Example: Access and modify a global variable inside a function ยท global_var = 100 # Declare global variable def access_global_variable_func(): # Accessing the said global variable print("Global variable value:", global_var) def modify_global_variable_func(): # Indicate that we are using the global variable global global_var # Update the global variable global_var += 50 access_global_variable_func() modify_global_variable_func() print("Value of the updated global variable:", global_var)
๐ŸŒ
Index.dev
index.dev โ€บ blog โ€บ how-to-set-global-variables-python
How to Set Global Variables Across Modules in Python
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.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ faq โ€บ programming.html
Programming FAQ โ€” Python 3.14.3 documentation
You could use a global variable containing a dictionary instead of the default value; itโ€™s a matter of taste. Collect the arguments using the * and ** specifiers in the functionโ€™s parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary.
๐ŸŒ
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 - 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.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ global-local-nonlocal-variables
Python Variable Scope (With Examples)
In Python, we can declare variables in three different scopes: local scope, global, and nonlocal scope. A variable scope specifies the region where we can access a variable. For example, ... Here, the sum variable is created inside the function, so it can only be accessed within it (local scope).
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ global-keyword
Python Global Keyword (With Examples)
However, if we try to modify the global variable from inside a function as: # global variable c = 1 def add(): # increment c by 2 c = c + 2 print(c) add() ... This is because we can only access the global variable but cannot modify it from inside the function.
๐ŸŒ
PythonHow
pythonhow.com โ€บ how โ€บ use-global-variables-in-a-function
Here is how to use global variables in a function in Python
# Define a global variable my_var = 10 # Define a function that uses the global variable def my_function(): # Declare the variable as global global my_var # Use the global variable my_var += 1 # Call the function my_function() # Print the global variable print(my_var)
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ assigning-global-variables
Assigning to global variables - Python Morsels
January 28, 2021 - I've assigned to global variables ... even though you often shouldn't. The trick to writing a global variable is to use the global statement: >>> def set_message(name): ......
๐ŸŒ
Dive into Python
diveintopython.org โ€บ home โ€บ learn python programming โ€บ functions in python โ€บ global and local variables
Global Variables in Python Functions - How to Use, Set and Update
May 3, 2024 - Learn about the scope of global variables in Python and how they can be accessed and modified by any function or module in the program.
๐ŸŒ
Medium
medium.com โ€บ @python-javascript-php-html-css โ€บ using-global-variables-in-python-functions-1719bdca0609
Global Variable Utilization in Python Functions
August 24, 2024 - How do I declare a global variable inside a function? You use the global keyword followed by the variable name. Can I access a global variable without using the global keyword? Yes, you can access it, but you cannot modify it without the global ...
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-global-variables-examples
Python Global Variables โ€“ How to Define a Global Variable Example
May 12, 2022 - So, when I first try to print the value of the variable and then re-assign a value to the variable I am trying to access, Python gets confused. The way to change the value of a global variable inside a function is by using the global keyword:
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
How to handle 'global' variables? - Python Help - Discussions on Python.org
May 8, 2024 - Hi, Newby question here. Iโ€™m creating a program that traverses a directory tree using os.walk. Each directory in that tree is checked for a distinct text file, the text file is opened, and the contents searched for image filenames & urls. I want to keep track of the total number of text files ...