Open mhmerrill opened 2 years ago
decorator example:
https://realpython.com/primer-on-python-decorators/#syntactic-sugar
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_whee():
print("Whee!")
get source code example:
https://www.adamsmith.haus/python/answers/how-to-get-the-source-code-of-a-function-in-python
def f():
x = 1 + 2
return(x)
source_code = inspect.getsource(f)
print(source_code)
OUTPUT
def f():
x = 1 + 2
return(x)
parse the source_code to get ast:
https://greentreesnakes.readthedocs.io/en/latest/tofrom.html
>>> tree = ast.parse("print('hello world')")
>>> tree
<_ast.Module object at 0x9e3df6c>
>>> exec(compile(tree, filename="<ast>", mode="exec"))
hello world
annotations:
https://realpython.com/lessons/annotations/#:~:text=Annotations%20were%20introduced%20in%20Python,D.
>>> import math
>>> def circumference(radius: float) -> float:
... return 2 * math.pi * radius
...
...
>>> circumference.__annotations__
{'radius': <class 'float'>, 'return': <class 'float'>}
>>> circumference(1.23)
7.728317927830891
some links for walking python ast
using the ast.NodeVisitor
and possibly ast.NodeTransformer
https://stackoverflow.com/questions/1515357/simple-example-of-how-to-use-ast-nodevisitor
https://docs.python.org/3/library/ast.html
https://gist.github.com/jtpio/cb30bca7abeceae0234c9ef43eec28b4
https://codemonkeytips.blogspot.com/2010/08/simple-python-nodevisitor-example.html
https://discuss.dizzycoding.com/simple-example-of-how-to-use-ast-nodevisitor/
https://www.educative.io/answers/what-is-astnodevisitor-in-python
https://www.programcreek.com/python/?code=jpush%2Fjbox%2Fjbox-master%2FServer%2Fvenv%2Flib%2Fpython3.5%2Fsite-packages%2Fpip%2F_vendor%2F_markerlib%2Fmarkers.py
investigate a flow which looks like: