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

I don't like either of your examples. Your first example should have been a generator and used a yield rather than a global counter. Your second example is simply bad practice (what do you even expect to happen? It's ambiguous, but i having the value 9 seems to make a reasonable amount of sense).



In my second example, I expect i to not be in the scope. The variable i only makes sense inside the list comprehension and should not be randomly introduced into the outer scope.

For the first example, I don't see how you could replace it with yield, especially if the function foo has to normally return a value when it's used. The core idea is to count how many times foo is called without altering the call site at all. Also, this is an entirely trivial example to illustrate the scoping issue; in practice, there are more complicated reasons to want to set non-local variables, especially from things like helper functions.


This scope-leaking was fixed in Python 3 afair (I don't have a Python 3 to verify just now).


The examples don't have to be idiomatic Python to demonstrate Python's weaknesses. In fact, one would expect mature idiomatic forms to skirt language limitations more-or-less by design.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

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

Search: