Python Definition Problem

I have a trivial example:


def func1():
    local_var = None

    def func(args):
        print args,
        print "local_var:", local_var

        local_var = "local"

    func("first")
    func("second")

func1()

I expect the output to be:

first local_var: None
second local_var: local

However, my actual conclusion is:

first local_var:
Traceback (most recent call last):
  File "test.py", line 13, in 
    func1 ()
  File "test.py", line 10, in func1
    func ("first")
  File "test.py", line 6, in func
    print "local_var:", local_var
UnboundLocalError: local variable 'local_var' referenced before assignment

My understanding of python review rules dictates that this should work properly. I have another code where this works as expected, but the reduction of one broken piece of code to it, the trivial example above also does not work. Therefore, I am at a standstill.

+3
4

local_var func func - print " " , - , . jtb, Python 3 nonlocal, , print, Python 2. Python 2 , , barename , , , , :

def func1():
    local_var = [None]

    def func(args):
        print args,
        print "local_var:", local_var[0]

        local_var[0] = "local"

    func("first")
    func("second")

func1()

, Python 2.2 , , ( , ).

+9

Python 3.0 . Python3 nonlocal, . nonlocal local_var func() . . PEP 3104.

Python 3, global -.

+1

pre-3.0 -

def func1():
    local_var = [None]

    def func(args):
        print args,
        print "local_var:", local_var[0]

        local_var[0] = "local"

    func("first")
    func("second")

func1()
+1

Python review rules are discussed and explained in this related question:

Reason for unintuitive behavior of UnboundLocalError

+1
source

Source: https://habr.com/ru/post/1713781/


All Articles