Default scope of variables

Joshua Landau joshua.landau.ws at gmail.com
Mon Jul 8 15:14:16 CEST 2013


On 8 July 2013 12:54, Neil Cerutti <neilc at norwich.edu> wrote:
> On 2013-07-07, Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
>> On Fri, 05 Jul 2013 13:24:43 +0000, Neil Cerutti wrote:
>>
>>> for x in range(4):
>>>    print(x)
>>> print(x) # Vader NOoooooOOOOOO!!!
>>
>> That loops do *not* introduce a new scope is a feature, not a bug. It is
>> *really* useful to be able to use the value of x after the loop has
>> finished.
>
> I don't buy necessarily buy that it's "*really*" useful

Just take "really" to mean "like, I'm totz not lying".

> but I do
> like introducing new names in (not really the scope of)
> if/elif/else and for statement blocks.
>
> z = record["Zip"]
> if int(z) > 99999:
>     zip_code = z[:-4].rjust(5, "0")
>     zip4 = z[-4:]
> else:
>   zip_code = z.rjust(5, "0")
>   zip4 = ""

I'd probably break down and cry if "if"s introduced a new scope in
Pythons before the "nonlocal" keyword (assuming current Python
semantics where "=" defaults to only the inner-most scope).



More information about the Python-list mailing list