Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restrict scopes of local variables in python

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.

like image 543
lunchbreak Avatar asked Jun 12 '17 20:06

lunchbreak


People also ask

Is there block scope in Python?

Here's a quick overview of what these terms mean: Local (or function) scope is the code block or body of any Python function or lambda expression. This Python scope contains the names that you define inside the function. These names will only be visible from the code of the function.

What is LEGB rule in Python?

The LEGB rule names the possible scopes of a variable in Python: Local, Enclosing, Global, Built-in. Python searches namespaces in this order to determine the value of an object given its name. Scopes are created with functions, classes, and modules.


1 Answers

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:

  • Create single-use functions or classes. The function would have to be called, whereas the class would never have to be named again after its definition, because class definitions are executed immediately.
  • 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.

like image 154
Kodiologist Avatar answered Oct 25 '22 04:10

Kodiologist