Last active
August 11, 2023 17:58
-
-
Save vadimkantorov/095e046f1cdcd5a1ba3ffe3fae350538 to your computer and use it in GitHub Desktop.
Intercepting python's builtin print function with two ways
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 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