[PYTHON] Variable scope when using internal functions

Nesting functions to use when you use it several times but you don't need to use it as a method for going out.

def hoge():
    def fuga():
        pass

I wondered what the handling of variables would be when using this, so I verified it.

Local variables

def hoge():
    x = 1
    def fuga():
        x = 3
    fuga()
    print(x)

Execution result

hoge()
1

In the case of local variables, it seems that they are treated as separate variables. Naturally natural. However, this can be changed with the nonlocal declaration.

def hoge():
    x = 1
    def fuga():
        nonlocal x
        x = 3
    fuga()
    print(x)

Execution result

hoge()
3

Class variables

class Sample:
    def __init__(self):
        self.hoge = None

def hoge():
    smp = Sample()
    smp.hoge = "abcde"
    def fuga():
        smp.hoge = "fghijk"
    fuga()
    print(amp.__dict__)

Execution result

hoge()
{'hoge': 'fghijk'}

I wonder if class variables will be treated globally.

bonus

You can use this to refresh your code when you want to put another value in a class variable depending on the condition

class Sample():
    def __init__(self):
        self.hoge = None
        self.fuga = None

def hoge(list):
    smp = Sample()
    def set_val(val1, val2):
        smp.hoge = val1
        smp.fuga = val2
    if len(list) == 1:
        set_val(list[0], None)
    else:
        set_val(list[0], list[1])
    print(smp.__dict__)

Execution result

hoge(['aaaa', 'bbbb'])
{'hoge': 'aaaa', 'fuga': 'bbbb'}

hoge(['cccc'])
{'hoge': 'cccc', 'fuga': None}

I don't know if there is any use for it!

Recommended Posts

Variable scope when using internal functions
Variable scope
About variable scope. .. ..
Summary when using Fabric
[Azure] Try using Azure Functions
Precautions when using Chainer
Memo using trigonometric functions
(Personal) points when using ctypes
Environment variables when using Tkinter
DEBUG settings when using Django
When using if and when using while
File structure when using serverless-python-requirements
Use configparser when using API
Small speedup when using pytorch