The story of manipulating python global variables

Global and local variables

I messed up several times while implementing it in python, so make a note for myself. It's understandable that this code returns the following result:

x = 1

def func1():
    print(x)

def func2():
    x = "hoge"
    print(x)

func1()
func2()

>>> 1
>>> hoge

In python, when referencing a variable, it goes to refer to the global scope if it is not declared inside the local scope.

Also, if the variable is not declared before rewriting the variable in the local scope, an error is returned.

def func3():
    y += 1
    y = 5
    print(y)

func3()

>>> Traceback (most recent call last):
>>>   File "/test.py", line 8, in <test>
>>>     func3()
>>>   File "/test.py", line 4, in func3
>>>     y += 1
>>> UnboundLocalError: local variable 'y' referenced before assignment

I understood it so far, but when global variables were involved, I was immediately confused. In other words, when you operate a variable that is declared as a global variable, you have to declare it explicitly, and an error is usually returned.

x = 1

def func4():
    x += 1 #You can't see x yet at this point
    x = 5 #At this stage the variable x is added to the local scope
    print(x)

func4()

>>> Traceback (most recent call last):
>>>   File "/test.py", line 8, in <test>
>>>     func4()
>>>   File "/test.py", line 4, in func4
>>>     x += 1 
>>> UnboundLocalError: local variable 'x' referenced before assignment

Then what should I do?

The solution is simple, and when you use a global variable, let's make it clear that it is a global variable.

x = 1

def func5():
    global x #Explicitly be a global variable
    x += 1 
    print(x)

def func6():
    x = 10 #Explicitly be a local variable
    x += 1
    print(x)

func5()
func6()

>>> 2
>>> 11

Recommended Posts

The story of manipulating python global variables
The story of Python and the story of NaN
The story of making Python an exe
[python] Checking the memory consumption of variables
The story of blackjack A processing (python)
the zen of Python
The story of sys.path.append ()
The story of low learning costs for Python
Image processing? The story of starting Python for
The story of reading HSPICE data in Python
The story of building Zabbix 4.4
Towards the retirement of Python2
The story of Python without increment and decrement operators.
[Apache] The story of prefork
About the ease of Python
The story of FileNotFound in Python open () mode ='w'
Declaration of C global variables
About the features of Python
The story of automatic language conversion of TypeScript / JavaScript / Python
The Power of Pandas: Python
The story of implementing the popular Facebook Messenger Bot with python
The story of how the Python bottle worked on Sakura Internet
Consideration for Python decorators of the type that passes variables
The story of rubyist struggling with python :: Dict data with pycall
What beginners learned from the basics of variables in python
[Python] Tensorflow 2.0 did not support Python 3.8, so the story of downgrading Python
Initializing global variables using Python decorators
[Python] The stumbling block of import
First Python 3 ~ The beginning of repetition ~
Existence from the viewpoint of Python
pyenv-change the python version of virtualenv
Using global variables in python functions
The story of the "hole" in the file
[Python] Understanding the potential_field_planning of Python Robotics
Review of the basics of Python (FizzBuzz)
The story of remounting the application server
About the basics list of Python basics
Story of power approximation by Python
The story of writing a program
Learn the basics of Python ① Beginners
The story that the version of python 3.7.7 was not adapted to Heroku
March 14th is Pi Day. The story of calculating pi with python
A story that struggled to handle the Python package of PocketSphinx
[Python] Variables
The story of making a standard driver for db with python.
The story of making a module that skips mail with python
[Python3] Dynamically define global variables in functions
Change the length of Python csv strings
The story of trying to reconnect the client
Check the behavior of destructor in Python
The story of an error in PyOCR
[Python3] Understand the basics of Beautiful Soup
Learn the basics while touching python Variables
Pass the path of the imported python module
The story of adding MeCab to ubuntu 16.04
Learning notes from the beginning of Python 1
[Python] Understand the content of error messages
[Python3] Rewrite the code object of the function
I didn't know the basics of Python
The story of making an immutable mold
[Python] Try pydash of the Python version of lodash