Title: Python Magic Methods — Set Corruption When __hash__ Missing
Open Graph Title: Python Magic Methods — Set Corruption When __hash__ Missing
Description: Orders missing from set when __eq__ defined without __hash__ triggers TypeError and silent corruption. Use frozen dataclasses or test set insertion.
Open Graph Description: Orders missing from set when __eq__ defined without __hash__ triggers TypeError and silent corruption. Use frozen dataclasses or test set insertion.
Opengraph URL: https://thecodeforge.io/python/magic-methods-python/
Domain: thecodeforge.io
{
"@context": "https://schema.org",
"@type": "TechArticle",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "https://thecodeforge.io/python/magic-methods-python/"
},
"headline": "Python Magic Methods — Set Corruption When __hash__ Missing",
"description": "Orders missing from set when __eq__ defined without __hash__ triggers TypeError and silent corruption. Use frozen dataclasses or test set insertion.",
"keywords": "Python Magic Methods — Set Corruption When __hash__ Missing, Python, Advanced, OOP in Python, Orders missing from set when __eq__ defined without __hash__ triggers TypeError and silent corruption. Use frozen dataclasses or test set insertion.",
"proficiencyLevel": "Expert",
"author": {
"@type": "Person",
"@id": "https://thecodeforge.io/about/#naren",
"name": "Naren",
"url": "https://thecodeforge.io/about/"
},
"publisher": {
"@type": "Organization",
"@id": "https://thecodeforge.io/#org",
"name": "TheCodeForge",
"url": "https://thecodeforge.io",
"logo": {"@type": "ImageObject", "url": "https://thecodeforge.io/assets/og-image.png"}
},
"datePublished": "2026-03-05T00:00:00+00:00",
"dateModified": "2026-08-30T00:00:00+00:00",
"url": "https://thecodeforge.io/python/magic-methods-python/",
"inLanguage": "en",
"educationalLevel": "Advanced",
"image": "https://thecodeforge.io/assets/og-image.png",
"isPartOf": {"@id": "https://thecodeforge.io/#website"}
}
{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
{"@type": "ListItem", "position": 1, "name": "Home", "item": "https://thecodeforge.io/"},
{"@type": "ListItem", "position": 2, "name": "Python", "item": "https://thecodeforge.io/python/"},
{"@type": "ListItem", "position": 3, "name": "Python Magic Methods — Set Corruption When __hash__ Missing", "item": "https://thecodeforge.io/python/magic-methods-python/"}
]
}
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [
{
"@type": "Question",
"name": "What is the most important magic method to implement in a custom class?",
"acceptedAnswer": {
"@type": "Answer",
"text": "__repr__. It provides an unambiguous string representation that helps immensely during debugging and logging. If you implement only one dunder, make it __repr__. Include the class name and constructor arguments, and mask any sensitive fields rather than omitting them."
}
},
{
"@type": "Question",
"name": "Can I add a magic method to an existing built-in type like list?",
"acceptedAnswer": {
"@type": "Answer",
"text": "You cannot monkey-patch dunder methods on built-in types because Python looks them up on the type, not the instance, and built-in types are implemented in C with immutable type structures. You can subclass the built-in type and override the dunder on the subclass."
}
},
{
"@type": "Question",
"name": "What happens if I implement __eq__ but not __hash__?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Python automatically sets __hash__ to None, making your objects unhashable. Attempting to add them to a set or use them as dict keys raises TypeError: unhashable type. If you want objects to be explicitly unhashable, set __hash__ = None yourself so the intent is documented in the code."
}
},
{
"@type": "Question",
"name": "Should I use @dataclass or manually implement magic methods?",
"acceptedAnswer": {
"@type": "Answer",
"text": "For simple data containers, prefer @dataclass (or @dataclass(frozen=True) for immutable value objects). It automatically generates __init__, __repr__, __eq__, and optionally __hash__. In Python 3.10+, @dataclass(slots=True) also generates __slots__ correctly. Use manual implementation when you need custom behaviour that dataclass cannot express, or when inheriting from a complex class hierarchy that predates dataclasses."
}
},
{
"@type": "Question",
"name": "Why does my __getattr__ method cause infinite recursion?",
"acceptedAnswer": {
"@type": "Answer",
"text": "The most common cause: inside __getattr__, you access self.some_attr where some_attr does not exist yet (usually during early __init__). That triggers __getattr__ again, recursively. The fix is the underscore guard: raise AttributeError immediately for any name starting with underscore. This stops the recursion because Python treats the AttributeError as a clean lookup failure rather than a reason to recurse. A second cause: __getattr__ accesses self._backing_dict before that attribute is set, triggering the same loop. Always set backing attributes using super().__setattr__ or object.__setattr__ in __init__ to bypass __setattr__ hooks and ensure they exist before __getattr__ can be called."
}
},
{
"@type": "Question",
"name": "When should I use __del__ for cleanup?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Almost never. __del__ is called when an object's reference count drops to zero, but it is not guaranteed to run in the presence of reference cycles (CPython's cycle garbage collector handles those separately), is never guaranteed in PyPy, and may not run at all during interpreter shutdown. If a resource must be released — file handles, sockets, database connections, GPU memory — use a context manager (__enter__/__exit__) with a with statement. If you need an explicit close() method, document it clearly. __del__ is acceptable only for optional logging or debugging, never for correctness-critical cleanup."
}
}
]
}
| og:type | website |
| og:image | https://thecodeforge.io/assets/og-image.png |
| og:image:width | 1200 |
| og:image:height | 630 |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: max-image-preview:large