Python: variables still available if defined in try or if?

I am a Python beginner and I am in the background of C / C ++. I am using Python 2.7.

I read this article: Pythons Namespace Beginner's Guide, Scope Resolution, and the LEGB Rule , and I think I have some understanding of Python about these technologies.

Today I realized that I can write Python code as follows:

if condition_1: var_x = some_value else: var_x = another_value print var_x 

That is, var_x is still available, even if it does not define before if. Since I am from C / C ++ background, this is something new for me, as in C / C ++, var_x defined in the area enclosed by if and else, so you can no longer access it if you do not define var_x before if .

I tried to find answers on Google, but since I am not familiar with Python yet, I don’t even know where to start and what keywords I should use.

I assume that in Python, if does not create a new scope. All variables that were defined in if are only in the area in which the if is located, and therefore the variable is still available after if . However, if var_x in the above example is defined only in if , but not in else , a warning will be issued that print var_x may refer to a variable that cannot be defined.

I have some confidence in my own understanding. However, can someone help correct me if I'm wrong somewhere, or give a link to a document that discusses this ??

Thanks.

+7
scope python
source share
1 answer

I assume in Python if no new scope is created. All variables that were recently defined in if are only in the area it is in, and therefore the variable is still available after if .

It is right. In Python, namespaces , which essentially define the scope of variables, are created only for modules and functions (including methods, basically any def ). So, everything that happens inside the function (and not in the subfunction) is placed in the same namespace.

It is important to know, however, that simply assigning a destination within a function will reserve a name in the local namespace. This leads to some interesting situations:

 def outer (): x = 5 def inner (): print(x) # x = 10 inner() outer() 

In the above code, when this line is commented out, the code will print 5 , as you might expect. This is because inner will look in the outer region of the name x . If you add the line x = 10 , but the name x will be local to inner , so an earlier look at x would look in the local namespace inner . But since it has not yet been assigned, you will get UnboundLocalError ("local variable x specified before the assignment"). A nonlocal operator was added in Python 3 to solve one problem: a situation where you want to actually change the x outer region inside the inner function.

For more information on finding a name, see this related question .

+10
source share

All Articles