On 9/26/2020 12:43 AM, Stephane Tougard via Python-list wrote:

[Example of Perl block scoping.]

===PYTHON===
#!/usr/local/bin/python
if 4 == 4:

if True:  # Only usefel in Python if you might might to switch to False.

     name = "Stephane"
     print(name)
     pass

Noise.  Only 'pass' when there is no other code.

print("Out {}".format(name))
============

The exact same code in Python works fine, the variable name is used
outside of the if block even it has been declared inside.

'name' is bound to a object, not declared
The only declarations are 'global' and 'nonlocal'.

Python only creates new scopes for class and function definitions. At least for CPython, comprehensions are implicit function definitions.

This does not look right to me.

Because you are accustomed to block scoping.

 Can we change this behavior

No.

or is there any point to keep it this way ?

Aside from not breaking most every existing Python program? If block scoped, one would have to add an otherwise useless fake declaration before the block to use the name outside the block. Python tries to avoid boilerplate code.

--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to