So you accidentally deleted some python files and now you want them back. There are 3 approaches to recover them.

Restore from backup

Surely you've got a backup of your crucial files, right?

A good strategy for backing up data is the 3-2-1 rule, which you can read more about here.

Restore from virtual control

If you're using git you can do the following command

git rev-list --abbrev-commit --pretty  --all [FILENAME]

This will find all commits that change that file and print it out in a nice list. Super useful if you know you had the file once, and need to recover it.

This commands only works on the current working tree, so if you're on the master branch it will not find files that were only ever committed to seperate branches and never merged in.

If the file was accidentally deleted during a rebase or a reset, then you might be able to find it by going back to a place where it existed using reflog.

git reflog

This provides a list of movements from branches, tags and commits. It gives a high level impression on what's going on and can let you go back to a previous state. The following command will go one step back.

git checkout HEAD@{1}

Restore from .pyc file

When python reads a file, it creates a .pyc file which is a compiled version of that file. This is done to making subsequent executions of that file faster.

We can restore the python file from the .pyc file using the uncompyle6 library, which you can find on PyPI. The following simple command utilizes it to decompile a python file

uncompyle6 *compiled-python-file-pyc-or-pyo*

You might there are some minor differences in whitespace and in missing comments from your original file, but that is a small price to pay to recover a file you thought lost.