Created
February 14, 2022 07:14
-
-
Save autf/cc8d804c51e7588f28df2ba509a118fd to your computer and use it in GitHub Desktop.
__new__ quacks like __call__
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class trace: | |
lv = 0 | |
# https://docs.python.org/3/reference/datamodel.html#object.__new__ | |
def __new__(cls, fn): | |
def wrapper(x): | |
indent = 4 * cls.lv * ' ' | |
cls.lv += 1 | |
print(indent + f'f({x})') | |
res = fn(x) | |
print(indent + f'-> {res}') | |
cls.lv -= 1 | |
return res | |
return wrapper | |
# replace `lru_cache` with `cache` if you're using Python 3.9+ | |
from functools import lru_cache | |
@trace | |
# @lru_cache | |
def fib(n): | |
if n < 2: return n | |
return fib(n-2) + fib(n-1) | |
# return fib(n-1) + fib(n-2) | |
fib(4) | |
# fib(10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment