Why does python behave this way with variables?

前端 未结 2 1265
自闭症患者
自闭症患者 2020-12-18 02:54

I have been trying to understand why python behaves this way, in the block of code below. I have done my research but couldn\'t find a good answer so I came here to see if a

相关标签:
2条回答
  • 2020-12-18 03:30

    Here's a rule for Python Scope Resolution from this answer

    LEGB Rule.

    L, Local — Names assigned in any way within a function (def or lambda)), and not declared global in that function.

    E, Enclosing-function locals — Name in the local scope of any and all statically enclosing functions (def or lambda), from inner to outer.

    G, Global (module) — Names assigned at the top-level of a module file, or by executing a global statement in a def within the file.

    B, Built-in (Python) — Names preassigned in the built-in names module : open,range,SyntaxError,...

    So basically in your question, the scope resolution is "from inside out" and since you aren't using the global keyword, the interpreter doesn't know to look outside the local function scope to find that variable var. All the interpreter sees is that you are using a variable before declaring and defining it, thus throwing the error. Global variables are often dangerous, and so Python wants to make sure you know you want to use a global variable by forcing you to be explicit about it.

    See this other answer for an explanation of the global keyword

    Hope it helps.

    0 讨论(0)
  • 2020-12-18 03:36

    Your var is defined as a global variable. In each function when you're only reading the var you're accessing the global var, but the moment there's an assigned value to var somewhere in the function, python treats every var within the function as a local variable. Thus why your last function failed, because print(var) (the local varaible) was called before var = 8 was assigned.

    You can read up a bit about more in these threads:
    How bad is shadowing names defined in outer scopes?
    Python nonlocal statement

    The best thing to do is be explicit about your code so it's no longer confusing if you're trying to reference a local, nonlocal or global variable.

    In this case, assuming your intention is to keep using the global var, do this:

    var = 5
    
    def func1():
        print(var)
    func1()
    
    def func2():
        global var
        var = 8
        print(var)
    func2()
    
    def func3():
        global var
        print(var)
        var = 8  # technically this is not necessary any more var = 8 was already assigned when func2() is called
    func3()
    

    The output is thus:

    5
    8
    8
    

    Edit: Thanks to juanpa.arrivillaga's comment - I missed your original question.

    How could I use a predefined global variable in a function, then define a local variable with the same name inside of the same function, without changing the value of the global variable ? ( in python of course )

    The short answer is - define the local var first like you did in func2() and you're good. The longer answer though is - why would you want to do that? It creates confusion and becomes a headache to track which is when you have variables of the same name in different scope. A better approach would be name your local var to be local_var or something so it's distinctly different and easily traced.

    0 讨论(0)
提交回复
热议问题