Skip to content

Instantly share code, notes, and snippets.

@Gerschel
Created February 21, 2020 08:33
Show Gist options
  • Save Gerschel/2215988335b835e5f1bea1a864d146f8 to your computer and use it in GitHub Desktop.
Save Gerschel/2215988335b835e5f1bea1a864d146f8 to your computer and use it in GitHub Desktop.
Get source of self-defined functions in interpreter; will need editing for your use; saves your butt when you write some cool stuff on the fly in the interpreter, and you like keeping cool stuff.
#!python3
"""
This file will need to be edited before each use, it's not copy and run
It's worth the trouble if you find yourself playing in the interpreter
and you get carried away and write a lot of code you don't feel like
losing.
"""
#from inspect import getsource //builtin, helps when files are saved
from dill.source import getsource #python3 -m pip install dill; usage, when in repl/interpreter/interactive shell
functions = []
#check dir to get a list of strings, the names of var/funcs to include or exclude in your conditional
for element in dir():
# whatever conditions, just don't forget to filter out dunder's, and your list that'll hold each function
if element[0] != '_' and element not in ('funcs', 'vars', 'excluded', 'functions'):
# since dir returns a list of strings, eval is needed, !NEVER EVAL USER INPUT! Just use it to save your cool stuff.
functions.append(getsource(eval(element)))
# Print nicely, getsource keeps newlines, double newline adds space between your functions
# This makes it easy to copy, for pasting into some file without all the ">>>" and "..."
for func in functions:
print(func, end="\n\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment