Skip to content

Instantly share code, notes, and snippets.

@vadimkantorov
Last active August 11, 2023 17:58
Show Gist options
  • Save vadimkantorov/095e046f1cdcd5a1ba3ffe3fae350538 to your computer and use it in GitHub Desktop.
Save vadimkantorov/095e046f1cdcd5a1ba3ffe3fae350538 to your computer and use it in GitHub Desktop.
Intercepting python's builtin print function with two ways
class Printer:
def __init__(self):
self.log = ''
def __repr__(self):
return self.log
def __call__(self, *args, **kwargs):
self.log += str(args) + '\n'
__builtins__.print(*args, **kwargs)
class print(metaclass = type('', (type,), dict(__repr__ = lambda self: print.log))):
log = ''
def __init__(self, *args, **kwargs):
print.log += str(args) + '\n'
__builtins__.print(*args, **kwargs)
if __name__ == '__main__':
print(1, 2, 3)
print(4, 5)
print(repr(print))
# 1 2 3
# 4 5
# (1, 2, 3)
# (4, 5)
print = Printer()
print(1, 2, 3)
print(4, 5)
print(repr(print))
# 1 2 3
# 4 5
# (1, 2, 3)
# (4, 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment