Skip to content

Instantly share code, notes, and snippets.

@ceshine
Created Feb 19, 2021
Embed
What would you like to do?
Demo of the @patch_to decorator from fastcore
from fastcore.basics import patch_to
class Demo:
val = 10
def __init__(self, val):
self.val = val
# ====================
# The default mode
# ====================
@patch_to(Demo)
def print(self):
print(self.val)
Demo(5).print() # prints 5
# =======================
# The class method mode
# =======================
@patch_to(Demo, cls_method=True)
def print(self):
print(self.val)
Demo(5).print() # prints 10
# =====================
# The property mode
# =====================
@patch_to(Demo, as_prop=True)
def print(self):
print(self.val)
Demo(5).print # prints 5
# =====================
# Addition notes
# =====================
#
# The function under @patch_to doesn't overwrite existing functions.
# In this example, the global `print` built-in function still works normally:
print("I am a print statement.") # prints I am a print statement.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment