todofixthis / class-registry

Registry pattern for Python classes, with setuptools entry points integration!
MIT License
40 stars 8 forks source link

Typed registry? #15

Closed VRichardJP closed 10 months ago

VRichardJP commented 10 months ago

One typical use case for ClassRegistry is to implement a plugin architecture, in which all registered class implement a common Protocol or inherit from a common ABC. To take your own example:

from class_registry import ClassRegistry

pokedex = ClassRegistry()

@pokedex.register('fire')
class Charizard(Pokemon):
  ...

@pokedex.register('grass')
class Bulbasaur(Pokemon):
  ...

@pokedex.register('water')
class Squirtle(Pokemon):
  ...

Here all registered class are Pokemon, so what about a TypedClassRegistry?

pokedex = TypedClassRegistry[Pokemon]()

# fails if Charizard does not implement `Pokemon`
@pokedex.register('fire')
class Charizard(Pokemon):
  ...

# automatic type hint: Pokemon
charizard = Pokedex['fire']

In such case the current ClassRegistry is just TypedClassRegistry[Any]

todofixthis commented 10 months ago

Kia ora @VRichardJP. Great idea, thanks for suggesting! Working on it now 😎

todofixthis commented 10 months ago

This rabbit hole goes surprisingly deep. Thinking about how I'm going to add automated tests for this, I decided to bring in mypy, and it turned up lots of issues 🙈

This plus #14 is probably going to require a new major release version.