Skip to content

Instantly share code, notes, and snippets.

@ceshine
Created February 19, 2021 05:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ceshine/318476922b8ed42aa7aaa7e0fac70c98 to your computer and use it in GitHub Desktop.
Save ceshine/318476922b8ed42aa7aaa7e0fac70c98 to your computer and use it in GitHub Desktop.
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