How do I get the source code of imported .py file, whcih does not exist anymore, in jupyter notebok?

Viewed 115

Question might seem confusing but let me explain.

I was working on a jupyter notebook. I had some of my functions and classes in .py files that I was using with importing them in the notebook. I accidentally deleted (rm) these .py files. However, they are still imported in jupyter notebook. Can I restore the code that exists in these .py files from jupyter notebook.

Details with example:

I had parser.py file.

I imported the class that I was going to use

from parser import Parser

I can still user Parser class, however, parser.py is gone. Hence, whenever I will stop this notebook. I will lose Parser forever...

1 Answers

If you can continue to modify the notebook where you have parser imported, you can try:

import inspect
print(inspect.getsource(parser))

This should print the contents of the module that was loaded when you originally imported Parser from parser.py. If that doesn't work, try replacing parser with Parser.

Taken from this answer on StackOverflow.

Related