🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Plugin Registries and Cached Properties in Python

Python OOPđŸŸĸ Free Lesson

Plugin Registries and Cached Properties in Python

Two problems recur in almost every non-trivial Python application. The first is extensibility: features arrive from other modules, other teams, or third parties, and the core must discover them without importing each one by hand. The second is cost: some attribute, such as a parsed configuration, a grouped index, or a compiled expression, is expensive to compute and stable for the lifetime of an object, yet the code reads it as if it were a plain field.

Both problems are solved by giving the class a little structure. A plugin registry turns "who is available" into data that can be enumerated, configured, and tested. A cached attribute turns an expensive computation into a one-time initialization that still looks like a normal attribute at the call site. This lesson builds both, with an eye toward the decisions that matter in production rather than the tricks that impress in a demonstration.

What You'll Learn

  • 1Design a plugin base class that registers subclasses and supports lookup by name
  • 2Load plugins from external modules without coupling the core to them
  • 3Implement and invalidate a cached attribute safely
  • 4Know when the standard library already solves both problems

Registration: what a plugin system owes its core

A registry is a mapping from a stable name to a class or factory. The interesting decisions are not the mapping itself but the contract around it: how names are validated, what happens on duplicate registration, whether plugins are instantiated eagerly or lazily, and how a plugin declares its configuration. Making those decisions explicit early keeps the system from growing an informal convention per feature.

python
class Plugin:
    registry = {}
    name = None

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        key = cls.name or cls.__name__.lower()
        if key in Plugin.registry:
            raise ValueError(f"duplicate plugin name: {key}")
        cls.name = key
        Plugin.registry[key] = cls

    def __init__(self, **config):
        self.config = config

    def activate(self):
        raise NotImplementedError

    def deactivate(self):
        pass


class JsonFormatter(Plugin):
    name = "json"

    def activate(self):
        return {"encoder": "json"}


class CsvFormatter(Plugin):
    name = "csv"

    def activate(self):
        return {"encoder": "csv"}


def build(name, **config):
    try:
        factory = Plugin.registry[name]
    except KeyError:
        raise ValueError(f"unknown plugin: {name}") from None
    instance = factory(**config)
    instance.activate()
    return instance


print(sorted(Plugin.registry))
print(build("json").config)

The duplicate check deserves emphasis. Silently overwriting an existing name turns a packaging mistake into a runtime mystery two weeks later. Raising at subclass creation time puts the failure in the module that caused it, which is where it belongs.

Discovery: importing the plugins on purpose

Registration only helps if the plugin modules actually run. In a small project, a single plugins.py that imports every implementation is honest and debuggable. In a larger one, plugins live in separate packages and the core must find them without a hard-coded import list. The standard mechanisms are package scanning for internal code and entry points for third-party distributions, which is how pytest, flake8, and Sphinx extensions are discovered.

python
import importlib
import importlib.util
import pkgutil
import pathlib


def discover(package_name):
    package = importlib.import_module(package_name)
    for module in pkgutil.iter_modules(package.__path__):
        importlib.import_module(f"{package_name}.{module.name}")
    return dict(Plugin.registry)


def discover_from_path(directory):
    for path in sorted(pathlib.Path(directory).glob("*.py")):
        if path.name.startswith("_"):
            continue
        spec = importlib.util.spec_from_file_location(path.stem, path)
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
    return dict(Plugin.registry)

Path-based loading is convenient for user-supplied scripts and dangerous for untrusted input, because executing a module runs arbitrary code. Keep the directory writable only by trusted users, and prefer entry points when the plugins ship as installable packages.

Caching an attribute without freezing the object

functools.cached_property is the standard tool: it stores the computed value in the instance dictionary under the attribute's own name, so the second access never calls the function again. For most applications that is the whole answer. Writing your own is justified only when you need something the built-in does not provide, such as a cache that lives outside the instance dictionary, or one that can be invalidated by a key.

python
from functools import cached_property


class SalesReport:
    def __init__(self, rows):
        self.rows = rows
        self._version = 0

    @property
    def version(self):
        return self._version

    def invalidate(self, name=None):
        self._version += 1
        for key in list(self.__dict__):
            if key.startswith("_cache_") or key in {"total", "by_region"}:
                if name is None or key == name:
                    self.__dict__.pop(key, None)

    @cached_property
    def total(self):
        return round(sum(row["amount"] for row in self.rows), 2)

    @cached_property
    def by_region(self):
        buckets = {}
        for row in self.rows:
            buckets.setdefault(row["region"], []).append(row["amount"])
        return {k: round(sum(v), 2) for k, v in buckets.items()}


report = SalesReport([
    {"region": "north", "amount": 12.5},
    {"region": "south", "amount": 8.0},
])
print(report.total, report.by_region)
report.rows.append({"region": "north", "amount": 4.0})
report.invalidate()
print(report.total)

Invalidation is the part teams skip. The version counter and the explicit invalidate method make staleness a decision rather than an accident. For a custom implementation, store the value under a private name so the public attribute stays a property, and remember that the instance dictionary is the cache: with __slots__ declared on the class, cached_property cannot work unless a __dict__ is included.

Concurrency, identity, and other edges

A cached property computed inside a lock is safe; computed outside one, two threads may both run the computation and one result wins. For expensive or side-effecting computations, guard the first computation with a lock, or accept the duplicate work and document it. Note also that cached_property requires a normal __set__-free descriptor path, so the attribute cannot also be a writable property on the same class.

Identity edges matter too. If two instances must share a parsed table, an instance-level cache is the wrong place; move it to a module-level cache keyed by an immutable identity such as a file path and a modification time. That keeps memory bounded and gives you a natural invalidation signal.

NeedUseInvalidation signal
Compute once per instancefunctools.cached_propertyExplicit deletion from the instance dictionary
Compute once per key globallyModule-level dict with a lockSize limit, TTL, or a version stamp
Recompute when inputs changeCustom property with a version checkAny mutation method bumps the version
Never recomputeClass-level constantNothing; it is immutable by design

Configuration and lifecycle beyond activate

A plugin that only exposes one method is a demo. Real plugins need a way to declare the configuration they require, a place for that configuration to come from, and a lifecycle that pairs activation with a guaranteed deactivation. Making the requirements visible in a class attribute, such as a required keys tuple or a small schema object, lets the host validate configuration before constructing anything and produce an error that names the missing key rather than the eventual KeyError deep inside activation.

Deactivation matters as much as activation. A plugin that opens a connection during activation must close it during deactivation, and the host must guarantee that deactivation runs on shutdown, on reload, and when activation itself fails halfway through. A small context-manager wrapper around the host's plugin collection is a natural way to get that guarantee, because the unwinding rules already exist and do not have to be reinvented.

Ordering is the last piece. If one plugin depends on another, the host needs a declared dependency rather than an import-order accident. Topological sorting of declared names is twenty lines and removes an entire class of startup bug that otherwise appears only under specific import orders, which is exactly the kind of bug that survives code review.

Cache keys, bounds, and eviction

An unbounded cache is a memory leak with good intentions. The practical design question is not how to store values but how to decide that a stored value may be forgotten. Three strategies cover most cases. A size bound with least-recently-used eviction keeps the hottest entries and caps memory predictably. A time-to-live bound suits values that drift out of date on their own, such as rates or configuration. A version bound ties validity to an explicit counter, which is the most precise option when you can enumerate every mutation that should invalidate.

The key design follows from the same reasoning. Include everything the computation actually depends on, and nothing else. A key that includes a timestamp will never hit; a key that omits the region will return the wrong region's result for the second caller. When the inputs are large or unhashable, hash them into a stable digest rather than storing the raw structure, and record the inputs alongside the value if debugging the cache will ever matter.

Whichever strategy you choose, expose the statistics. A cache that reports hits, misses, and current size turns tuning from folklore into a measurement, and it is the fastest way to discover that a cache has a one hundred percent miss rate because the key includes something volatile.

When not to build either thing

A plugin system costs indirection. If the set of implementations is fixed and lives in one repository, a plain dictionary of factories defined next to the code that uses it is easier to read and search. Add discovery only when plugins genuinely arrive from elsewhere.

The same restraint applies to caching. Profile first: an attribute that takes a millisecond and is read a thousand times a day does not need a cache, and the invalidation logic will cost more in review time than the computation ever cost in CPU. Reach for the cache when the measurement says the computation is a real share of the request time, and write the invalidation test before the cache ships.

Common Mistakes

Allowing a duplicate plugin name to overwrite silently

Fix: Raise at subclass creation so the conflicting module is the one that fails loudly

Caching an attribute with no way to invalidate it

Fix: Expose an invalidate method that pops the cached entry and is called from every mutating path

Using cached_property on a class that declares __slots__ without __dict__

Fix: Either include __dict__ in the slots or store the cache under an explicit private slot

Building a discovery mechanism for plugins that all live in one repository

Fix: Import them directly in a single module until an external plugin boundary actually exists

Best Practices

  • Validate plugin names at registration and fail on duplicates immediately
  • Load external plugins through entry points rather than executing arbitrary paths
  • Use functools.cached_property unless you have a concrete reason not to
  • Give every cache an explicit invalidation story and a test that proves it works
  • Measure the cost of a computation before deciding it needs caching

Interview Questions

Q1: Why register plugins in __init_subclass__ instead of a decorator?

Subclass creation happens whenever the module is imported, so registration cannot be forgotten, and the base class stays free of per-plugin decorators that third-party authors would have to remember.

Q2: How does cached_property differ from a property?

A property calls its function on every access. cached_property calls it once, stores the result in the instance dictionary under the same name, and returns the stored value thereafter.

Q3: What breaks cached_property?

Instances of classes with __slots__ and no __dict__ have nowhere to store the value, and defining both a cached_property and a setter under the same name is a conflict. Threaded first access can also compute twice without a lock.

Key Takeaways

  • A plugin registry is a contract: names, duplicates, lifecycle, and configuration
  • Discovery through import or entry points removes hard-coded dependency lists
  • cached_property stores results in the instance dictionary, so invalidation is deletion
  • Every cache needs an explicit invalidation path and a test for staleness
  • Build neither system until the requirement is real; simpler code is a feature
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement