Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Python is in a larger bind because it only has function scoping and variable declaration is implicit. It does not have sub-function scopes.

So does not really have a good way to fix the issue, even by using a different keyword as JS did.

OTOH default parameters being evaluated at function definition make mitigating it relatively simple.



Yeah, block scoping is one of those "weird CS ideas" that I'm sure at some point early in Python's design was deemed too complicated for the intended audience, but is also quite a natural way to prevent some human errors. JavaScript made the same mistake and later fixed it (let/const).


I'm not a computer scientist so I can't rule whether function scope was a mistake, and can't see how block scoping would be considered too complicated, I personally think it fits much better with my mental model. Then again, Python doesn't have blocks in the traditional sense of the word IIRC, in C style languages the accolades are a pretty clear delineator.

Parts of my previous job were terrible because it had JS functions thousands of lines of code long where variables were constantly reused (and often had to be unset before another block of code). That said, that wasn't the fault of function scope per se, but of a bad but very productive developer.


TBF you can have block scoping in an indentation-based language, though it probably help to merge the too, as in Haskell: `let…in` will define variables in the `let` clause, and those variables are only accessible in the `in` clause (similarly case…of)


I love python, but it's one of the biggest annoyances. Local variables like in Lua make a lot of sense.


Python does actually have a single instance of sub-function scopes: When you say `try: ... except Exception as e: ...` the `e` variable is deleted at the end of the `except` clause. I think this is because the exception object, via the traceback, refers to the handling function's invocation record, which in turn contains a map of all the function's local variables. So if the variable worked like normal variables in Python it'd create a reference cycle and make the Python GC sad. So if you need that behaviour, you need to reassign the exception to a new name [0].

0: https://docs.python.org/3/reference/compound_stmts.html#the-...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: