The __getitem__ method in Python can do more than simple lookups: Use [] for custom logic — returning filenames, random numbers, or database records.
Want your Python object to support bracket notation []? Define __getitem__:
Python gotcha: Forgetting () on method calls! Result: Error: ‘builtin_function_or_method’ object is not iterable Remember: () calls the method!
Think “from modname import funcname” saves memory in Python? It doesn’t! (Lots of people think it does.) The full module still loads (see sys.modules). The only difference: “modname” isn’t in your namespace, just “funcname”. “from import” is convenient. It doesn’t save memory.
Heard about __new__, the constructor in Python? You can basically forget about it. It’s for advanced, unusual cases. Just use __init__! It runs automatically on every new instance. __init__ is for assigning attributes to self (what other languages call “instance variables”).
Using uv? The Python version is stored in .python-version. Change it with But: uv gives an error: 3.13 is incompatible with requires-python in pyproject.toml of ‘>=3.14.’
Want to get the unique values from a Python list? Use a set! Of course, list elements must be hashable!
Sorting a Python dict by value? Instead of: Use itemgetter. It’s cleaner AND ~25% faster: Sort by value, then by key:
Write to a file in Python with open(filename, ‘w’). What if filename already exists? Its contents are gone. (I hope you have backups!) Instead, try: If filename already exists, ‘x’ raises an exception. For new files, ‘x’ and ‘w’ are the same.
Use parentheses to split long Python code across lines: But with parentheses, Python sees it as one line: Or in comprehensions…