Python Magic Methods

Magic methods (also called dunder methods) are special methods surrounded by double underscores that let you define how your class instances interact with Python’s built-in operations. When you use + on two objects, Python calls __add__. When you call len(), Python calls __len__. This reference covers the most commonly used magic methods organized by category. Initialization and Lifecycle Method Triggered By Purpose __init__(self, ...) MyClass() Initialize instance attributes __new__(cls, ...) Before __init__ Control instance creation (rarely needed) __del__(self) Object garbage collected Cleanup (prefer context managers instead) class User: def __init__(self, name, email): self.name = name self.email = email user = User("Carl", "carl@example.com") String Representation Method Triggered By Purpose __str__(self) str(obj), print(obj) Human-readable string __repr__(self) repr(obj), REPL display Developer/debug string __format__(self, spec) format(obj, spec), f-strings Custom formatting class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"Point({self.x}, {self.y})" def __str__(self): return f"({self.x}, {self.y})" p = Point(3, 4) print(repr(p)) # Point(3, 4) print(p) # (3, 4) Comparison Operators Method Operator __eq__(self, other) == __ne__(self, other) != __lt__(self, other) < __le__(self, other) <= __gt__(self, other) > __ge__(self, other) >= from functools import total_ordering @total_ordering class Temperature: def __init__(self, celsius): self.celsius = celsius def __eq__(self, other): return self.celsius == other.celsius def __lt__(self, other): return self.celsius < other.celsius freezing = Temperature(0) boiling = Temperature(100) print(freezing < boiling) # True print(freezing >= boiling) # False (from @total_ordering) With @total_ordering, you only need __eq__ and one of __lt__/__gt__ — Python derives the rest. ...

March 22, 2023 · Carl Sampson

The 5 coolest things about using Python

Python has numerous cool features that make it one of the most popular programming languages in the world. Here are five that stand out — with code to prove it. 1. Readability and Simplicity Python’s clean syntax emphasizes readability, making it easy for both beginners and experienced programmers to understand code at a glance: # Reading a file is straightforward and safe with open("data.txt") as f: for line in f: print(line.strip()) The with statement handles resource cleanup automatically. The intent of the code is obvious. Compare this to the equivalent boilerplate in Java or C++ and the difference is striking. ...

March 21, 2023 · Carl Sampson

Some XXE Payloads

XML External Entity (XXE) injection exploits applications that parse XML input without disabling external entity resolution. If the XML parser is misconfigured (which many are by default), an attacker can define custom entities that read local files, make network requests, or cause denial of service. These payloads are for authorized security testing only. What is XXE? When an XML parser processes a document, it can resolve entities defined in the DOCTYPE declaration. External entities use the SYSTEM keyword to reference files or URLs. If the parser resolves these without restriction, the attacker controls what the server reads and where it sends data. ...

March 14, 2023 · Carl Sampson

Content Security Policy

Content Security Policy (CSP) is a browser security mechanism that controls which resources a web page is allowed to load. By declaring a policy via HTTP header, you tell the browser exactly which scripts, styles, images, fonts, and connections are permitted. Anything not explicitly allowed is blocked. CSP is one of the most effective defenses against Cross-Site Scripting (XSS) and data injection attacks. How CSP Works CSP is delivered as an HTTP response header: ...

February 23, 2023 · Carl Sampson

Context Managers in Python

Context managers are Python’s answer to resource management — ensuring that files get closed, locks get released, and database connections get returned to the pool, even when exceptions occur. The with statement makes this pattern concise and reliable. The with Statement The most common context manager is open() for file handling: with open("example.txt", "w") as file: file.write("Hello, World!") # File is automatically closed here, even if write() raises an exception Without with, you’d need a try/finally block: ...

February 22, 2023 · Carl Sampson