Python scoping problem

╄→гoц情女王★ 提交于 2019-12-06 03:52:31
Alex Martelli

The assignment to local_var in func makes it local to func -- so the print statement references that "very very local" variable before it's ever assigned to, as the exception says. As jtb says, in Python 3 you can solve this with nonlocal, but it's clear from your code, using print statements, that you're working in Python 2. The traditional solution in Python 2 is to make sure that the assignment is not to a barename and thus does not make the variable more local than you wish, e.g.:

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()

the assignment to the indexing is not to a barename and therefore doesn't affect locality, and since Python 2.2 it's perfectly acceptable for nested inner functions to refer to variables that are locals in outer containing functions, which is all this version does (assigning to barenames is a different issue than referring to variables).

The standard way to solve this problem pre-3.0 would be

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()
ire_and_curses

Python's scoping rules are discussed and explained in this related question:

Reason for unintuitive UnboundLocalError behaviour

Before Python 3.0, functions couldn't write to non-global variables in outer scopes. Python3 has introduced the nonlocal keyword that lets this work. You'd add nonlocal local_var at the top of func()'s definition to get the output you expected. See PEP 3104.

If you're not working in Python 3 you'll have to make the variable global, or pass it into the function somehow.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!