Check if a cell is a valid standalone module

Viewed 21

I’d like to be able to export the contents of some cells programmatically, but before doing so I’d like to check if the cell would run as a standalone python module/file.

Is there a way of quickly executing a cell via the API in a blank/fresh context to check if it would run by itself?

The manual version of this process for reference is to copy the contents of a cell into a new python file, then run it with python newfile.py and eliminate the NameErrors one by one.

1 Answers

The best I can think of is to mess with the globals() object. That's where all top-level names are stored. You might be able to do something like this (I haven't tested it):

# top of code, to get clean globals
from copy import copy
original_globals = copy(globals())
del original_globals["copy"]

... # misc code

# now you want to check if it would work standalone, so set globals to original state
new_globals = copy(globals())
for name in new_globals:
    if name not in original_globals:
        del globals()[name]

... # do something standalone


# reset global state
for name, value in new_globals.items():
    globals()[name] = value

Not foolproof by any means (e.g. if you redefine a global like sum, but that's a bad idea generally anyway), but it should catch most what you're looking for. I would also look into implementing this feature as a context manager, so you could make it as simple as:

with restore_initial_global_state():
    ... # do something standalone
Related