2 ms·
Consider the common pattern: with open(path) as file: result = func(file.read()) another_func(result) If `with` used a separate scope then it
by pphysch 5y ago
Consider the common pattern:
with open(path) as file:
result = func(file.read())
another_func(result)
If `with` used a separate scope then it would be a lot less ergonomic. How might we bring data outside that scope and be confident that `with` isn't forcibly cleaning things up? Would be a lot more verbose.
- shakna 5y agoI think you've missed what I've meant by a new binding. That the body executes is entirely intuitive. However: with open(path) as file: ... if file.mode == 'r': print("Huh? file is still a thing?")
- xscott 5y agoPython doesn't have block scope, but most people don't seem to notice: def foo(): if False: x = 123 print("x is visible out here:", x) That will generate an error because `x` is "referenced before assignment", but the variable exists for the entire function. This can bite you in subtle ways: x = "is global out here" def foo(): print("all good:", x) def bar(): print("not good:", x) if False: x = "now x is local, even before this declaration"