It's a topic that may be scolded by devout Pythonistas, but in a situation where you want to do things in an embedded Python environment without polluting the namespace, I created a local scope using code like the one below. I've confirmed that it works with Python 2.7.4 / 3.3.1.
localscope.py
DummyClassForLocalScope = "global value"
try:
class DummyClassForLocalScope:
# you can write any code here
raise RuntimeError("Exit from local scope")
except RuntimeError as exception:
if exception.args != ("Exit from local scope",):
raise exception
print(DummyClassForLocalScope)
I'm just canceling the class creation by creating a local scope with the class statement and raising an exception at the end of the local scope.
I don't want to use it a lot even if I make a mistake, but if you really want to do something like (function () {...} ());
in JavaScript, there is also such a method.
Recommended Posts