class-resolver

raw JSON →
0.7.1 verified Fri May 01 auth: no python

A lightweight library for looking up and instantiating classes by name or key, with support for registration, aliases, and presets. Current version 0.7.1, requires Python >=3.10, weekly releases.

pip install class-resolver
error AttributeError: module 'class_resolver' has no attribute 'ClassResolver'
cause Misspelled or incorrect import name. The module is `class_resolver` (with underscore), not `classresolver`.
fix
from class_resolver import ClassResolver
error KeyError: 'xyz'
cause Attempted to lookup a class that is not registered in the resolver.
fix
Check registered names with resolver.names or ensure the class is properly added.
error TypeError: __init__() got an unexpected keyword argument 'unexpected'
cause Passed an unexpected keyword argument to `resolver.make()`. In versions >=0.7.0, extra kwargs are passed to the constructor, which may cause an error if the class does not accept them.
fix
Remove unexpected kwargs or filter them before calling make().
gotcha Class names are lowercased by default for lookup (e.g., 'MyModel' -> 'my_model'). To preserve original case, pass `suffix=''` or customize `suffix` parameter.
fix Use `ClassResolver(classes, suffix='')` or override with custom normalization.
gotcha `ClassResolver.from_subclasses()` only finds subclasses that are imported. If you define classes in separate modules, ensure they are imported before calling `from_subclasses`.
fix Import all subclass modules explicitly before calling `from_subclasses()`.
breaking In version 0.7.0, `ClassResolver.make()` now passes extra kwargs to the constructor. Previously, extra kwargs were ignored. This may break code that relied on silent ignoring.
fix Ensure that kwargs passed to `make()` are valid constructor arguments for the resolved class.
deprecated The `Optional` alias for `Contributions` is deprecated since 0.7.0. Use `Contributions` directly.
fix Replace `Optional` with `Contributions` in type hints.

Create a resolver from a base class or a list of classes, then look up and instantiate by registered name.

from class_resolver import ClassResolver

class MyModel:
    name = 'my_model'

class AnotherModel:
    name = 'another_model'

resolver = ClassResolver.from_subclasses(MyModel)
# Or manually:
# resolver = ClassResolver([MyModel, AnotherModel])

# Look up by name or class
model_class = resolver.lookup('my_model')
# Instantiate with parameters
instance = resolver.make('my_model', param1=10)
print(instance)