Skip to content

Instantly share code, notes, and snippets.

@Techcable
Created January 29, 2025 01:58
Show Gist options
  • Save Techcable/e97c460a4196786114f89a30119b401c to your computer and use it in GitHub Desktop.
Save Techcable/e97c460a4196786114f89a30119b401c to your computer and use it in GitHub Desktop.
Examples of how `str(x)` differs from `x.__str__()`
"""
Examples of how `str(x)` differs from x.__str__`()
This behavior is documented here: https://docs.python.org/3.11/reference/datamodel.html#special-lookup
The reason for this is performance, so `x + y` can avoid a dictionary lookup and/or `__getattribute__` call
"""
def override_str(*args):
return "bar"
class MagicBehavior:
def __str__(self):
return "foo"
def __getattribute__(self, name):
if name in ("__str__"):
return override_str
else:
raise NotImplementedError # fallback to standard lookup
print(MagicBehavior().__str__()) # prints 'bar', not 'foo'
print(str(MagicBehavior())) # prints 'foo', not 'bar'
class InstanceOverride:
def __str__(self):
return "foo"
instance = InstanceOverride()
instance.__str__ = override_str
print(instance.__str__()) # prints 'bar' not 'foo'
print(str(instance)) # prints 'foo' not 'bar'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment