Python has no such way to do this, although it does have locals and globals functions that can give you access to the entire local or global namespace. But if you want to select the selected variables, I find it better to use inspect . Here is the function that should do this for you:
def compact(*names): caller = inspect.stack()[1][0] # caller of compact() vars = {} for n in names: if n in caller.f_locals: vars[n] = caller.f_locals[n] elif n in caller.f_globals: vars[n] = caller.f_globals[n] return vars
Make sure it works in any Python environment that you use. Usage will be as follows:
a = 1 b = 2 def func(): c = 3 d = 4 compact('b', 'd') # returns {'b': 2, 'd': 4}
I donโt think there is a way to escape without quotes around variable names.
source share