What is the Python way to avoid referencing before assignment errors in spanning areas?

I am talking about the general case. Here is an example:

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

This code will return the following error: NameError: free variable 'c' referenced before assignment in enclosing scope . Although the logical assumption is that the output should be 1 . What is the Pythonic solution to this problem? Use global or nonlocal (which I don't like)? Maybe just avoid situations where several areas use common variables with the same name?

+4
source share
1 answer


Passing it as a parameter

When passing an external variable as a parameter, avoid reusing names, if it is not possible that this variable can process any other variable as a parameter, then it does not really matter, otherwise it will be confusing if you go through d next and you perform operations with c inside the function.

Secondly, the value of c will not be changed inside the function even if the name is changed from param to c (this makes very little sense) when passed as a variable, since it is not considered as a global variable, even if this variable is an object, it will only an object in this function unless you pass it to a class.

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

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

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

Here is what I would recommend:

 c = 1 def a(param): def b(): print(param) b() param = 2 return param c = a(c) 

Or even:

 c = 1 def b(param): print(param) def a(param): b(param) param = 2 return param c = a(c) 
+5
source

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


All Articles