4

That moment you find out that python is very sloppy when it comes to scopes. It seems that variables declared in loops are callable in function scopes. So this code actually does not give any errors:

for i in range(6):
print i

print(“out of loop scope”, i)

Now I’m just like: WTF! That can cause some serious errors when you’re not aware of this thing. I don’t know any other language that has this property...

Comments
  • 0
  • 0
    Yeah, one of these things making me want to KMS every time those Quant traders pass over a zip folder “here’s the new code, you guys can productionise it” Whoever had this idea making Python defacto “Data Scientists” language should _____ ____ themselves...
  • 0
    ... python!

    Pick Ruby instead 😊
  • 1
    Well, not sloppy, but consequent.

    Consider this: A scope in python is anything which is at the same indent or any indent more on the right.. (think of nested blocks)

    > if True:
    > x = 23
    > # x is valid here
    > # but not here

    Now the twist: The for loop does two things at the same time: Declaring a variable and opening a new block.
    Because the for loop itself is part of the outer block, the variable is declared there and will also be available in the outer block.

    I feel this is the most logical behavior, never had any issues with it.

    Try not to use single character variable names, and while you’re on it, do yourself a favor and use Python 3.

    Python 2 is (very soon) unsupported, and contains many illogical pitfalls..

    Btw: JavaScript has sloppy scoping, as variables from inner scopes are available outside (if declared with var)
Add Comment