Why does Python allow me to define a variable in one scope, but use it in another?

I see that it is possible to define a variable inside a region, but then refer to it outside this region. For example, the following code works:

if condition: x = 5 else: x = 10 print x 

However, this seems a little strange to me. If you try to do this in C, the variable X will not be correctly defined:

 if(condition) { int x = 5; } else { int x = 10; } print x; // Doesn't work: x is unavailable! 

The solution, in any case, is to first declare X, THEN to figure out what to do with it:

 int x; if(condition) { x = 5; } else { x = 10; } print x; // Works! 

So in Python, my instinct is to write code as follows:

 x = None if condition: x = 5 else: x = 10 print x 

However, I understand that Python does not require this from me. Any suggestions? Is there any style for this scenario?

+7
source share
4 answers

Blocks do not create a new scope in Python. Modules, classes and functions do.

also:

 x = 10 if condition: x = 5 print x 

or

 x = 5 if not condition: x = 10 print x 
+17
source

My suggestion:

Write Python, not C.

In Python, we use blocks. if is a block. A block does not necessarily mean a different scope in Python.

+5
source

In your example, you can try the following:

 x = 10 if condiiton: x = 5 print x 

As for why Python doesn't have the same scope rules, such as C (both C ++ and Java), the short answer is that they are different languages. A long-term response is associated with effectiveness. In C, these coverage rules are processed at compile time, and there is no runtime overhead. In Python, it will have to save the inner area in a new dict , and this will add extra overhead. I am sure there are other reasons, but this is a great practical option.

0
source

You are not creating a new scope, so there is no problem defining the scope.

However, note that if you do something like:

 if foo: x = 10 print x 

You will get a NameError value if foo is False, so you may run into a situation where you really want to define your variable outside the conditional expression (or add else to set it to None .)

0
source

All Articles