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 →

object() in Python 2026: Base Class & Minimal Instance Creation + Modern Use Cases

Built In Function Mar 24, 2026

object() in Python 2026: Base Class & Minimal Instance Creation + Modern Use Cases

The built-in object() is the most fundamental class in Python — every class inherits from it by default if no other base class is specified. Calling object() creates a plain, empty instance with no attributes or methods beyond those defined in object itself. In 2026 it remains the go-to base class for minimal objects, sentinel values, type annotations, metaprogramming, and as a safe starting point when you want no inherited behavior except the basics (__str__, __repr__, __eq__, etc.).

With Python 3.12–3.14+ improving object creation speed, enhancing free-threading safety for simple instances, and better type system support (Self, TypeGuard), object() is still the lightest possible object you can create. This March 24, 2026 update covers how object() behaves today, real-world patterns (sentinels, base classes, minimal mocks), performance notes, and best practices for using it in modern, type-safe Python code.

TL;DR — Key Takeaways 2026

  • object() → creates a minimal instance with only object methods
  • Default base class for all user-defined classes if no parent is specified
  • 2026 best practice: Use object() as explicit base for clean hierarchy; use instances as sentinels or minimal mocks
  • Main use cases: sentinel values, base class in inheritance chains, lightweight placeholders, testing mocks
  • Performance: Extremely lightweight — smallest possible object footprint

1. Basic Usage — Creating Minimal Objects


o = object()
print(type(o))          # <class 'object'>
print(dir(o))           # ['__class__',
                        #  '__delattr__',
                        #  '__dir__',
                        #  ...,
                        #  '__str__']

print(hasattr(o, "x"))  # False
try:
    o.x = 10            # plain object() has no __dict__
except AttributeError as e:
    print(e)            # 'object' object has no attribute 'x' ...

2. Real-World Patterns in 2026

Sentinel Values (Unique Markers)


MISSING = object()  # unique sentinel — guaranteed not equal to any real value
settings = {"theme": "dark"}

def get_setting(key: str, default=MISSING):
    if key in settings:
        return settings[key]
    if default is MISSING:
        raise KeyError(f"Setting {key} not found")
    return default

print(get_setting("theme"))          # dark
print(get_setting("lang", "en"))     # en

Minimal Base Class / Clean Inheritance


class Base:
    pass  # implicitly inherits from object

# Explicit minimal base (cleaner intent)
class MinimalBase(object):
    pass

class MyClass(MinimalBase):
    def __init__(self):
        super().__init__()

Lightweight Mock / Placeholder Objects in Tests


def test_feature(mock_obj = object()):
    # Minimal object with no side effects
    if hasattr(mock_obj, "method"):
        mock_obj.method()
    else:
        print("No method — using fallback")

3. object() vs Alternatives – Comparison 2026

Approach Size / Overhead Methods Best For
object()Minimal (~48 bytes)Only object methodsSentinels, minimal bases
type("Sentinel", (), {})SmallOnly object methodsCustom sentinel with name
object.__new__(object)MinimalOnly object methodsLow-level creation
Simple class with passSmallobject methods + __dict__When you need __dict__

4. Best Practices & Performance in 2026

  • Use object() for sentinels — guaranteed unique & minimal footprint
  • Explicit base class — inherit from object() for clarity in new-style classes
  • Type hints 2026:
    
    from typing import Any
    
    def is_sentinel(obj: Any) -> bool:
        return obj is MISSING
    
    MISSING = object()
    
  • Performance: object() creation is extremely lightweight — smallest possible object
  • Free-threading (3.14+): Safe — immutable structure, no shared mutable state

What object() Gives You

object is the base class of every Python class. An instance created with object() has no attributes and cannot gain new ones, because it has no __dict__. What it does have is a unique identity: it equals only itself. That makes it ideal as a sentinel, a marker that can never be confused with real data such as None, 0 or an empty string.

Worked Example: Telling "Missing" Apart from None

This cache lookup must distinguish a stored None from a missing key.

_MISSING = object()

cache = {"user:1": None}       # None is a valid cached result

def lookup(key):
    value = cache.get(key, _MISSING)
    if value is _MISSING:
        return "not cached"
    return f"cached: {value!r}"

print(lookup("user:1"))   # cached: None
print(lookup("user:2"))   # not cached

Using None as the default would make both lookups look the same.

Common Mistakes

  • Comparing sentinels with ==: use is
  • Setting attributes on object(): it raises AttributeError; use types.SimpleNamespace
  • Writing class A(object): harmless but unnecessary in Python 3

Quick Summary

  • object() creates a unique, empty instance
  • Perfect for sentinels
  • Use SimpleNamespace for quick attribute bags

Conclusion — object() in 2026: Minimal & Foundational

object() is the root of Python’s type hierarchy and the lightest possible object you can create. In 2026, use it for unique sentinels, explicit base classes, minimal mocks, and as a safe starting point for inheritance. It’s fast, memory-efficient, and one of Python’s most fundamental building blocks — essential for clean, predictable, and performant object-oriented code.

Next steps:

  • Use object() as a sentinel in your next optional-value function

Related Tutorials

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