Skip to content Skip to sidebar Skip to footer

What Is The Pythonic Way To Avoid Reference Before Assignment Errors In Enclosing Scopes?

I'm speaking about the general case. Here's an example: c = 1 def a(): def b(): print(c) b() c = 2 a() This code will return the following error: NameError: f

Solution 1:

Passing it as a parameter

When passing a outside variable as a parameter, avoid reusing names unless it's not possible that this variable can handle any other variable as parameter, then it doesn't really matter otherwise it will be confusing if you pass d the next time and you do operations on c within the function.

Secondly, the value ofcwill not get modified within the function even if changing name from param to c (it has very little meaning) when passing as a variable because it's not considered as a global varaible, even tho the variable is an object it will only be a object in this function unless you pass it into a class.

c = 1defa(param):
    defb():
        print(param)
    b()
    param = 2

a(c)

You would need to stick to the global option if you don't want to pass it as a parameter and you still want to affect c outside of your function. The global option will affect the "outside" c variable as your want it to.. but this is not really considered best practice, avid it if possible.

c = 1def a():
    global c
    def b():
        print(c)
    b()
    c = 2

a()

Here's what i would recommend:

c = 1defa(param):
    defb():
        print(param)
    b()
    param = 2return param

c = a(c)

Or even:

c = 1defb(param):
    print(param)
defa(param):
    b(param)
    param = 2return param

c = a(c)

Post a Comment for "What Is The Pythonic Way To Avoid Reference Before Assignment Errors In Enclosing Scopes?"