vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns str() in Python 2026: String Conversion + Modern Formatting & Best Practices type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns super() in Python 2026: Method Resolution & Modern Inheritance Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices round() in Python 2026: Rounding Numbers + Modern Precision & Use Cases reversed() in Python 2026: Reverse Iteration + Modern Patterns & Best Practices repr() in Python 2026: Official String Representation + Modern Debugging & Serialization Use Cases pow() in Python 2026: Power & Modular Exponentiation + Modern Use Cases & Best Practices property() in Python 2026: Properties, Getters/Setters & Modern Patterns ord() in Python 2026: Unicode Code Point from Character + Modern Use Cases & Best Practices open() in Python 2026: File Handling + Modern I/O Patterns & Best Practices range() in Python 2026: Efficient Sequence Generation + Modern Patterns & Best Practices print() in Python 2026: Output Formatting + Modern CLI & Debugging Patterns View all in this category →

hash() in Python 2026: Object Hashing, Hashability & Modern Use Cases

Built In Function Mar 23, 2026

hash() in Python 2026: Object Hashing, Hashability & Modern Use Cases

The built-in hash() function returns the hash value of an object — an integer used for fast lookup in dictionaries and sets. In 2026 it remains a fundamental part of Python’s hash table implementation and is critical for understanding hashability, custom hashing (__hash__), caching, deduplication, and performance in data structures.

With Python 3.12–3.14+ introducing deterministic hashing in more contexts, better free-threading safety for hash tables, and improved type hinting for hashable types, hash() is more predictable and performant. This March 23, 2026 update explains hash() behavior, hashability rules, real-world patterns (caching, custom classes), security notes (hash randomization), and best practices for reliable hashing in modern Python.

TL;DR — Key Takeaways 2026

  • hash(obj) → returns integer hash value (if object is hashable)
  • Hashable types: immutable built-ins (int, str, tuple, frozenset), user classes with __hash__
  • 2026 best practice: Never rely on hash value stability across runs (hash randomization enabled by default)
  • Main use cases: dict/set keys, caching (lru_cache), deduplication, custom hash tables
  • Security note: Hash randomization prevents hash-flooding attacks — do not use hash() for security-sensitive operations
  • Performance: Extremely fast — used internally for O(1) lookups

1. Basic Usage — Hash Values


print(hash(42))             # integer hash (stable within run)
print(hash("hello"))        # string hash
print(hash((1, 2, 3)))      # tuple hash (immutable)
print(hash(frozenset([1,2])))  # frozenset hash

# Unhashable types raise TypeError
# hash([1,2])               # TypeError: unhashable type: 'list'

2. Real-World Patterns in 2026

Caching with lru_cache


from functools import lru_cache

@lru_cache(maxsize=128)
def compute_with_config(config: frozenset[str]) -> int:
    # frozenset is hashable → works as cache key
    return len(config) * 100

print(compute_with_config(frozenset(["ml", "data"])))  # 200

Custom Hashable Class


class Point:
    def __init__(self, x: int, y: int):
        self.x = x
        self.y = y

    def __hash__(self):
        return hash((self.x, self.y))

    def __eq__(self, other):
        if not isinstance(other, Point):
            return False
        return (self.x, self.y) == (other.x, other.y)

p1 = Point(1, 2)
p2 = Point(1, 2)
print(hash(p1) == hash(p2))  # True
print({p1, p2})              # set with one item

Deduplication with frozenset keys


def deduplicate_by_keys(items: list[dict], key_fields: frozenset[str]):
    seen = set()
    result = []
    for item in items:
        key = frozenset((k, item.get(k)) for k in key_fields)
        if key not in seen:
            seen.add(key)
            result.append(item)
    return result

3. Hashability Rules & Comparison 2026

Type Hashable? Reason 2026 Use Case
int, float, str, boolYesImmutableDict keys, caching
tuple (immutable contents)YesImmutableComposite keys
frozensetYesImmutableSet of items as key
list, dict, set, bytearrayNoMutableAvoid as keys
Custom class with __hash__ & __eq__Yes (if implemented correctly)User-definedCustom objects in sets/dicts

4. Best Practices & Performance in 2026

  • Implement __hash__ & __eq__ consistently — equal objects must have same hash
  • Type hints 2026:
    
    from typing import Hashable
    
    def cache_key(key: Hashable) -> int:
        return hash(key)
    
  • Never rely on hash stability — hashes change between runs (hash randomization enabled)
  • Performance: hash() is extremely fast — O(1) average for lookups
  • Free-threading (3.14+): Hash tables are thread-safe for reads; use locks for writes

Conclusion — hash() in 2026: Hash Table Foundation

hash() is the engine behind Python’s fast dicts and sets — simple to call, but powerful in its implications for performance and correctness. In 2026, implement __hash__ carefully for custom classes, use frozenset for hashable sets, and never depend on hash stability across runs. It’s fast, reliable, and one of Python’s most important tools for efficient data structures and caching.

Next steps:

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices