Skip to content

Instantly share code, notes, and snippets.

@anthonyraf
Created January 22, 2023 14:30
Show Gist options
  • Save anthonyraf/5dc69338e0cf7986483f300ec9eb60bb to your computer and use it in GitHub Desktop.
Save anthonyraf/5dc69338e0cf7986483f300ec9eb60bb to your computer and use it in GitHub Desktop.
Overwrite python function __repr__ and __str__
class CustomFunction:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __str__(self):
return "A custom function"
def __repr__(self):
return "<custom function>"
def my_function(name):
return f"Hello {name}!"
my_function = CustomFunction(my_function) # You can also use @CustomFunction decorator directly on the function declaration
print(my_function("John")) # => Hello John!
list_for_testing_repr = [my_function]
print(list_for_testing_repr) # => [<custom function>]
print(my_function) # => "A custom function"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment