[PYTHON] When a local variable with the same name as a global variable is defined in the function

The variable bar in the function definition below is interpreted as a global variable because there is no definition of bar in the function block.

def foo():
    print(bar)

The code below succeeds because the global variable bar is defined before calling foo.

bar = 4

def foo():
    print(bar)

foo()  # => 4

You can see the global variables of foo in the attribute co_names of the code object of foo.

foo.__code__.co_names  # => ('print', 'bar')

By the way, in Python's official documentation, co_names is written as the local variable name tuple, but (local variable name) (Excluding free variables) Name error.

The bar in the function definition below is interpreted as a local variable because the bar is defined in the function block.

def foo():
    print(bar)
    bar = 3
foo.__code__.co_names  # => ('print',)

You can see the local variables of foo in the attribute co_varnames of the code object of foo.

foo.__code__.co_varnames  # => ('bar',)

This interpretation is determined when the function definition is made, so even if there is a bar before the definition of bar, it will not be interpreted as a global variable, and an error will occur as follows.

bar = 4

def foo():
    print(bar)
    bar = 3

foo()  
# => UnboundLocalError: local variable 'bar' referenced before assignment

In other words, the name in the function block is determined to be a global variable or a local variable (or a free variable) at the stage of function definition, and it is not rebound from a global variable to a local variable at the time of assignment to the name.

In addition, comprehensions such as lists introduce a new scope, but only the iterables corresponding to the first for are interpreted in the outer scope. The example below succeeds, because of the three bars in the list comprehension, the rightmost bar is interpreted as the scope of foo, that is, the global variable bar.

bar = range(3)

def foo():
    print([bar for bar in bar])

foo()  # => [0, 1, 2]

Recommended Posts

When a local variable with the same name as a global variable is defined in the function
When the variable name conflicts with the Devaga command in pdb
Get the variable name of the variable as a character string.
Load the module with the same name in another location
A memo when checking whether the specified key exists in the defined dictionary with python
Get the class name where the method is defined in the decorator
The value of meta when specifying a function with no return value in Dask dataframe apply
When reading an image with SimpleITK, there is a problem if there is Japanese in the path
The story I was addicted to when I specified nil as a function argument in Go
Precautions when creating a two-dimensional array with all the same values
Automatically rename a node with the same name found while working
Workaround for the problem that sys.argv is not passed when executing a Python script with only the file name in Python2.7 on Windows
[Python] Execution time when a function is entered in a dictionary value
A story when a directory is buggy with the django-admin start project command in a virtual environment using Pipenv
Memorandum (Add name only to people with the same surname in the list)
Replace the directory name and the file name in the directory together with a Linux command.
The eval () function that calculates a string as an expression in python
Behavior when returning in the with block
Precautions when pickling a function in python
[Python] Get the variable name with str
When the target is Ubuntu 16.04 in Ansible
When changing the table name with flask_migrate
Find a building on Google Earth that is the same height as Shingodzilla
Turn multiple lists with a for statement at the same time in Python
[Python] I tried to get the type name as a string from the type function
[Python] Get the files in a folder with Python
Access files in the same directory as the executable
(Note) Importing Excel with the same column name
Get the caller of a function in Python
Detect folders with the same image in ImageHash
[Solution] When inserting "0001" into the column of string in sqlite3, it is entered as "1".
When the variable you want to superscript with matplotlib is two or more characters
[Introduction to Python] What is the important "if __name__ =='__main__':" when dealing with modules?
I asked the problem of the tribonacci sequence in C ++ & the number of function calls when writing with the recurrence function (python is also available)
[Python] If you create a file with the same name as the module to be imported, an Attribute Error will occur.
Check if the string is a number in python
This is a sample of function application in dataframe.
How to get the variable name itself in python
When the selected object in bpy.context.selected_objects is not returned
Get the file name in a folder using glob
Embedding in datetime when only the time is known
What's in that variable (when running a Python script)
A simple difference when passing a pointer as a function argument
Determine if an attribute is defined in the object
Creating a list when the nomenclature is a fixed time
What does the last () in a function mean in Python?
Check the argument type annotation when executing a function in Python and make an error
What to do when a Missing artifact occurs in a jar that is not defined in pom.xml
I also tried to imitate the function monad and State monad with a generator in Python
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
Create a test with the auxiliary tool [selenium katalon recorder], which is convenient when using selenium.