Class Resolver 0.4.2 Documentation
The class_resolver
package helps you look up related classes and functions to parametrize your code.
Getting Started
An example might be when you have several implementations of the same algorithm
(e.g., fast, greedy one and a slow but correct one) and want to write a function
run_algorithm
that can be easily switched between them with a string corresponding
to the name of the implementation
from class_resolver import ClassResolver, Hint
class Algorithm:
def run(self, data):
...
class GreedyAlgorithm(Algorithm):
...
class CorrectAlgorithm(Algorithm):
...
algorithm_resolver = ClassResolver.from_subclasses(Algorithm)
def run_algorithm(data, *, algorithm: Hint[Algorithm] = "greedy"):
algorithm = algorithm_resolver.make(algorithm)
return algorithm.run(data)
Note that the string keys in the class resolver are "greedy"
for GreedyAlgorithm
and "correct"
for CorrectAlgorithm
. That’s because it knows the name of the base
class is Algorithm
and it can infer what you mean.
Pass a string, class, or instance
The Hint[Algorithm]
signifies that the algorithm_resolver.make(...)
function is very powerful. You can pass
it one of the following:
A string, like
"GreedyAlgorithm"
or"Greedy"
or"greedy"
and it deals with casing and the suffixA class like
GreedyAlgorithm
,CorrectAlgorithm
, or any potential subclass ofAlgorithm
An instance of an
Algorithm
, in case you have one pre-defined.None
, if you defined thedefault=...` when you called ``ClassResolver.from_subclasses
like inClassResolver.from_subclasses(Algorithm, default=GreedyAlgorithm
.
Getting Started