0

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.

  • 1
    Possible duplicate of [Viewing all defined variables](https://stackoverflow.com/questions/633127/viewing-all-defined-variables) – Chris_Rands Jul 07 '17 at 10:20

1 Answers1

0

After writing this question I found the answer:

def main(c):
    a, b = 1, 2
    # long function body with lots of variables...
    return locals()

seems to do the trick.

My previous example doesn't work because eval(expression, globals=None, locals=None) would need to be given a scope with a, b, c.