The Python Game Book

code games. learn Python.

User Tools

Site Tools


Sidebar

Github:

en:glossary:g:global_variables

global variables

All variables that are defined outside a function (and outside a class), are global variables.

All variables that are defined inside a function (or inside a class) are local variables

Python has a global statement to make a variable global, see also scope of variables

not to be confused with:

  • globals() - shows all global variables of the current module

see also:

how to avoid global variables

To avoid the use of global reasons why not to use global you can either:

  • create a class variable (directly below the class definition, before the __init__ function. All class variables can be accessed and modified from outside the class as well as from inside the class.
  • create a module (like config.py) and import this module in all your modules. Put your variable declarations inside this module. You can access and change the values from other modules

global keyword

A variable defined inside a function does not exist outside this function. But when you use global variablename inside the function, the variable act like a global variable and exist outside the function… after you called the function.

# x is NOT defined yet
>>>def make_x():
       x = 42
       
>>>x # will throw error
NameError: name 'x' is not defined
>>>make_x() # function call
>>>x # will still throw error
NameError: name 'x' is not defined
>>>def make_y():
       global y
       y = 42
    
>>>y # error, because y is not yet defined
NameError: name 'y' is not defined
>>>make_y() # function call
>>>y
42

The correct way for a function to make a local variable into a global one is to have a return value.

en/glossary/g/global_variables.txt · Last modified: 2020/12/15 19:16 by horst