Check if a cell is a valid standalone module

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.

You can use the nbformat package to load your notebook as a dictionary, then iterate over the cells and extract the source code of the ones you want to test. Once you extract the code, you can execute it to see if they work.

To identify the cells, you can add tags, then have your script extract the source of the cells with such tag.