5 ms·
One of my biggest gripes with python is the fact that the only way to create a local scope for variables is with functions. I understand if statements not havi
by DemetriousJones 2y ago
One of my biggest gripes with python is the fact that the only way to create a local scope for variables is with functions.
I understand if statements not having their own scope for simplicity's sake, but the fact that `with` blocks don't is simply mind-bobbling to me.
```
with open("text.txt", 'w') as f:
f.write("hello world")
f.write("hello world") # at least the handle was automatically closed so it will give an IO error
```
- DemetriousJones 2y agoSorry for the borked code formatting
- orf 2y agoIt’s actually very useful to have context managers outlive their with blocks. They are not only used for files: One example would be a timing context manager: with Timer() as t: … print(t.runtime) Another example is mocks, where you want to inspect how many times a mock was called and with what arguments, after the mock context manager has finished.
- DemetriousJones 2y agoI know it makes sense in the "scope-less" python philosopy but it still feels weird for me as a scope (ab)user in C++ and has caused me one headache or two in the past
- neongreen 2y agoI learned about the `scoping` package today. Idk if it works exactly as I expect from other langs, though.