Skip to content

Instantly share code, notes, and snippets.

@mahdiPourkazemi
Last active April 16, 2024 15:04
Show Gist options
  • Save mahdiPourkazemi/5b210bb7d000ef623c2087fdcd2b83cf to your computer and use it in GitHub Desktop.
Save mahdiPourkazemi/5b210bb7d000ef623c2087fdcd2b83cf to your computer and use it in GitHub Desktop.
debugger tools to debug python code by decoration (monitoring input and output)
import functools
def debugger(func):
"""Print the functon singnature and return value"""
functools.wraps(func)
def debugger_wraper(*args,**kwargs):
#list of input args
args_repr = [repr(a) for a in args]
#list of input kwargs
kwargs_repr = [f'{k} = {v!r}' for k, v in kwargs.items()]
#sum of the input values
signature = ', '.join(args_repr + kwargs_repr)
#print name of function and values
print(f"Calling {func.__name__} ({signature})")
value = func(*args,**kwargs)
print(f'Finished {func.__name__!r} returned {value!r} ')
return value
return debugger_wraper
#example one
@debugger
def make_greeting(name, age=None):
if age is None:
return f"Howday {name}!"
else:
return f"Whoa {name}! {age} already , you are growing uyp!"
#call make_greeting
make_greeting("mahdi", age=22)
#example two
import math
math_factorial = debugger(math.factorial) # == @debugger
def approximate(terms=18):
return sum(1 / math_factorial(n) for n in range(terms))
#call approximate
approximate(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment