uaveiro-leci/1ano/1semestre/fp/aula10/traced.py

52 lines
1.3 KiB
Python
Raw Permalink Normal View History

2022-12-20 17:57:02 +00:00
# New decorator: @traced
#
# PLEASE NOTE:
# This is not a required subject!
# You don't need to understand how this works.
# Just use the module as a service to trace the execution of functions.
#
# Decorator @traced modifies the function so that an execution trace is shown.
# jmr@ua.pt 2016-10-14 (v2)
# 2017-12-03: Name changed from trace -> traced
def traced(func):
def tracedfunc(*args, **kwargs):
if traced.indent != None:
indent = traced.indent # save current indentation
traced.indent += u"\u2502 "
print(u"{}{}{!r}{!r}".format(indent, func.__name__, args, kwargs))
try:
r = func(*args, **kwargs) # CALL the func!
2022-12-20 17:57:02 +00:00
return r
except Exception as e:
r = e
raise e
finally:
if traced.indent != None:
print(u"{}\u2514>{!r}".format(indent, r))
traced.indent = indent # restore indentation
2022-12-20 17:57:02 +00:00
return tracedfunc
2022-12-20 17:57:02 +00:00
# Initial tracing prefix:
traced.indent = ""
# Uncomment to turn off tracing by default:
# traced.indent = None
2022-12-20 17:57:02 +00:00
# traced.indent = traced.__dict__.get("indent")
2022-12-20 17:57:02 +00:00
if __name__ == "__main__":
# How to use this module:
from traced import traced
2022-12-20 17:57:02 +00:00
@traced
def func(x):
return x * x
2022-12-20 17:57:02 +00:00
func(3)