Sometimes I find that I have to use functions with long names such as os.path.abspath and os.path.dirname a lot in just a few lines of code. I don’t think it’s worth littering the global namespace with such functions, but it would be incredibly helpful to be able to define a scope around the lines where I need those functions. As an example, this would be perfect:
import os, sys
closure:
abspath = os.path.abspath
dirname = os.path.dirname
# 15 lines of heavy usage of those functions
# Can't access abspath or dirname here
I’d love to know if this is doable somehow
Python doesn’t have a temporary namespace tool like let in Lisp or Scheme.
The usual technique in Python is to put names in the current namespace and then take them out when you’re done with them. This technique is used heavily in the standard library:
An alternative technique to reduce typing effort is to shorten the recurring prefix:
Another technique commonly used in the standard library is to just not worry about contaminating the module namespace and just rely on __all__ to list which names you intend to make public. The effect of __all__ is discussed in the docs for the import statement.
Of course, you can also create your own namespace by storing the names in a dictionary (though this solution isn’t common):
Lastly, you can put all the code in a function (which has its own local namespace), but this has a number of disadvantages: