Reputation: 161
When there is a long function, how to limit the scope of variables within only a section of the function? I know in many languages one can do this with {}. How to do this in python?
I am aware that a separate function for just that section will encapsulate variables to its local namespace. But for a long, linear function, many people argue that it does not make sense to write many functions (and thus names) that are only called once.
Upvotes: 11
Views: 4615
Reputation: 3495
Generally speaking, you can't. Python only creates scopes for modules (files, generally), classes, and functions; variables can have a more limited lifetime only in a few special cases, like the target_list
in a list comprehension in Python 3. There's no block-level scope like in Perl.
So, your possible workarounds are:
del
variables when you're done with them.Fun fact: coming to terms with this limitation of Python is what finally got us to get rid of let
in Hy, because there's no way to make it work as one would expect. Update 5 years later: yet another version of let
is implemented, and the way it works is by implementing our own entire system for tracking the scopes of variables, and enforcing it by issuing compile-time errors and adding nonlocal
and global
when needed. I guess there are no shortcuts here.
Upvotes: 9