I use the following approach (code below) to add all the local variables from a function to the global namespace. Is there a better way to do this?
This specific case is not for general practice, but for debugging some process automation. The idea is to dump the local variables of certain functions into global and then filtering/saving the globals() entry. So than they can be loaded for a debugging session.
### Function Def ###
### This is function where you create some
# variable that you want to add to the
# "globals()" or global namespace
#
def create_local_var(add2globals = False):
if (add2globals):
locals_keys_pre = list(locals().keys())
C_key = "C_value"
D_key = "D_value"
if (add2globals):
locals_keys_post = list(locals().keys())
### Filtering the entries of "locals_keys_pre"
# from the "locals_keys_post" so that only
# the newly created variables in this function
# are included in the "newLocalsKeyList" list
newLocalsKeyList = [item for item in locals_keys_post if item not in locals_keys_pre]
for key in newLocalsKeyList:
### Adding the variables created in the
# local namespace to the global namespace
globals()[key] = locals()[key]
return
#
Now calling the "create_local_var" function
########## Main ##########
### Declaring a switch to turn on/off the
# capability to add variables from the
# local namespace to the global namespace
add2globals = True
# Listing the entries already in the "globals()"
globals_key_pre = list(globals().keys())
# Creating some variables
A_key = "A_value"
B_key = "B_value"
### Calling the fuction to create some
# local variables
create_local_var(add2globals)
### Listing the entries in the "globals()"
# after creating variables
globals_key_post = list(globals().keys())
### Filtering the entries of "globals_key_pre"
# from the "globals_key_post" so that only
# the newly created variables are included
# in the "newKeyList" list
newKeyList = [item for item in globals_key_post if item not in globals_key_pre ]
for key in newKeyList:
str2print = str(key) + " : " + str(globals()[key])
print(str2print)
#
Running the code with "add2global = False" will leave the variables created in the "create_local_var" functions in the local namespace. And, running the code with "add2global = True" will add all the variables created in the "create_local_var" functions to the global namespace. Below are the outputs for add2global = True/False
Output (with, add2global = False):
globals_key_pre : ['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'create_local_var', 'add2globals']
A_key : A_value
B_key : B_value
Output (with, add2global = True):
globals_key_pre : ['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'create_local_var', 'add2globals']
A_key : A_value
B_key : B_value
C_key : C_value
D_key : D_value
locals_keys_pre : ['add2globals']