Skip to content

Instantly share code, notes, and snippets.

@disconnect3d
Last active October 21, 2020 09:23
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 disconnect3d/e8fa65188d938a9bce55 to your computer and use it in GitHub Desktop.
Save disconnect3d/e8fa65188d938a9bce55 to your computer and use it in GitHub Desktop.
Python - An attempt to disable possibility to monkeypatch method (NOTE: This can't be done right; don't do this at home)
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return "Person: {}".format(self.name)
if __name__ == "__main__":
def __str__(self):
return "xoxoxo"
Person.__str__ = __str__
print(Person("Krzysztof"))
class StrMonkeypatchDisabler(type):
def __setattr__(self, key, value):
if key != '__str__':
print(
"{cls}.__setattr__({key}, {value})"
.format(cls=self.__class__.__name__, key=key, value=value)
)
super().__setattr__(key, value)
else:
print("Monkey patching '__str__' is disabled")
class Person(metaclass=StrMonkeypatchDisabler):
def __init__(self, name):
self.name = name
def __str__(self):
return "Hello {}!".format(self.name)
def __setattr__(self, key, value):
print("Attempt to set {key}".format(key=key))
if key != '__str__':
super().__setattr__(key, value)
else:
print("You can't monkeypatch __str__!")
if __name__ == "__main__":
def __str__(self):
return "xoxoxo"
p = Person("That works")
p.__str__ = __str__
print(p)
Person.__str__ = __str__
print(Person("Krzysztof"))
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return "Person: {}".format(self.name)
def __setattr__(self, key, value):
print("Attempt to set {key}".format(key=key))
if key != '__str__':
super().__setattr__(key, value)
else:
print("You can't monkeypatch __str__!")
if __name__ == "__main__":
def __str__(self):
return "xoxoxo"
p = Person("Almost working")
p.__str__ = __str__
print(p)
Person.__str__ = __str__
print(Person("Krzysztof"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment