Wednesday, October 28, 2009

Block Scoping

Unlike languages like Java, C++ and Perl, Python does not have block scoping. I.e. if you define a variable inside a loop in Python, it will still be in scope after that loop and will override previous bindings to that name. Python instead delimits scope at the levels of module, class and function. I defer to the authoritative source for the gory details. Note that according to the definitions used therein, Python does have block-level scoping, but that is only if you define block delimiters to be modules, classes and functions :-)

Python scoping is a drawback in the sense that if you are used to (Java/C++/Perl) block scoping, you are likely to accidentally introduce bugs as a result of using the same variable at different block levels. I've introduced a few such bugs. On the other hand, Python scoping eliminates the need to pre-define/declare variables which are set in a loop/if block, yet you need access to afterward. So, even though I've been burned by this style of scoping, I find that it helps me write better (i.e. more readable) code.

No comments:

Post a Comment