Question
How do I automate a function to return all variables defined inside its scope?
Motivation
When using Python for scientific work my scripts tend to be very linear (algorithm like) but quite long. When working interactively with the script I want to keep the calculated variables to further explore or use them.
I could just skip using a main()
function inside my scripts and do everything globally. However that would prohibit behavior like in the example below and prohibit me from modifying the script from an interactive python console prior to execution.
Example
Inside script.py
:
def main(c):
a, b = 1, 2
# long function body with lots of variables...
return parse_scope()
Inside the interactive console:
>>> import script
>>> script.main(c=3)
{'a': 1, 'b': 2, 'c': 3}
parse_scope()
captures the function scope and returns it as a dict, list,...
Ideas
def main(c):
a, b = 1, 2
# long function body with lots of variables...
return {name: eval(name) for name in dir()}
Gives NameError: name 'a' is not defined
.