Block scope in Python - Stack Overflow: "No, there is no [python] language support for creating block scope. The only means to create scope is functions, classes or modules."
Someone else goes on to say: "The idiomatic way in Python is to keep your functions short. If you think you need this, refactor your code! :) "I could very much like Python - but whenever I try to use it, I run into things like this very quickly.
I like Python's use of indentation.
But I imagine that the reasoning runs like this:
- Python uses indentation and hence doesn't need {...} to provide blocks for constructs like IF, functions, etc.
- But since Python doesn't have {...} blocks, we have no way to provide lexial scope except for def: and class: and modules.
- "Who needs it anyway?" says the chorus of unimaginative twerps. "Just refactor".
So think about refactoring: you could introduce a function with def, and then call it immediately. Must make sure tat the function cannot be called from elsewhere, but Python allowing local definitions (not-quite-closures) is sufficient for that. But that requires typing the name in twice.
I have been doing the following in some python code:
statement1
statement2
if 1:
statement3.1
statement3.2
statement4
when I want to emphasize the relatedness of statements3.1 and 3.2.
The equivalent of
in Perl or C.statement1
statement2
{
statement3.1
statement3.2
}
statement4
(Amusingly, emacs often requires me if add an if(1) to the blocks {}. It doesn't like indented "blocks in space". After all, what crazy person would want to create lots of local blocks?)
I like indicating the relatedness.
Plus, if I need a temporary variable or to import a function, I like to be able to do so in the smallest scope possible.
Yes, it can be refactored to be a function that is immediately invoked. But that is repetitive.
This explores aspects of one of my rules "The most important thing in programming is the ability to give something a name. The second most important thing is to not be required to give something a name."
Python requires scopes to have names. It fails the second most important test.
---
The obvious way to support scopes in an indentation oriented language like Python would be:
i.e. introduce a keyword "scope" or the like.statement1
statement2
scope:
statement3.1
statement3.2
statement4
1 comment:
Post a Comment