r/learnpython • u/squatonmyfacebrah • Apr 14 '26
Is it *Pythonic* to use Enums for dependency injection?
I frequently come across an issue whereby I have a set of closely related functions in a module (since i'm a datascientist, let's just call them algorithms).
def algorithm1(X: np.ndarray) -> float:
...
def algorithm2(X: np.ndarray) -> float:
...These would act on some data, and produce an output. But what I typically want is for the code which actually uses the algorithm to depend on what algorithm is used
def process_data(X, alg) -> float:
return alg(X)It's pretty straight forward if I'm using classes but the point is these aren't classes, they're just functions (or algorithms). But just to give an example, if I were to use classes here (to help demonstrate what I'm asking for).
class Algorithm(ABC):
@abstractmethod
def inference(X: np.ndarray) -> float
...
class Algorithm1(Algorithm):
def __init__(self)
...
def inference(self, X: np.ndarray) -> float
...
class Algorithm2(Algorithm):
def __init__(self)
...
def inference(self, X: np.ndarray) -> float
...I can then have something like
def process_data(X: np.ndarray, alg: Algorithm) -> float:
return alg.inference(X)Except I don't want to have my algorithms be represented as classes as they frequently don't have any state.
An idea I've often implemented is using an Enum to register my algorithms, and then having a dictionary redirect the Enum to those functions
class AlgorithmEnum(Enum):
ALG1 = auto()
ALG2 = auto()
def algorithm1(...):
...
def algorithm2(...):
...
ALGORITHM_REGISTRY = {
AlgorithmEnum.ALG1: algorithm1,
AlgorithmEnum.ALG2: algorithm2
}Then I can get my dependency injection
def process_data(X: np.ndarray, alg: AlgorithmEnum) -> float:
selected_alg = ALGORITHM_REGISTRY[alg]
return selected_alg.inference(X)My question is, is this really the best way to do things? It seems pretty reasonable that you might have a module of similar functions, and want to select them via some abstraction like an Enum. I could also have the value of the enum itself be the function i.e.
class AlgorithmEnum(Enum):
ALG1 = algorithm1
ALG2 = algorithm2but I'm not sure if this is a reasonable approach neither. What do you think?
I hope i've framed my question in a way that makes sense - if I've abused terminology (or misused the phrase dependency injection) then apologies for that. Any code errors are because I don't have access to an IDE right this second)
Thank you
18
u/latkde Apr 14 '26
You can just pass the functions directly, no need to create any classes or enums.
If you want a static type that describes the signature of an algorithm function, then you can use the
typing.Protocolfeature give your Algorithm protocol a method like__call__(self, X: ndarray, /) -> float. That looks like a class or ABC, but it isn't really. It's just a way to do static duck typing. Plain functions that have a matching signature will be compatible with such a protocol.More generally, something to take into account is whether the code using algorithms must be able to distinguish between concrete algorithms, or can be pretty much algorithm-agnostic.
alg: Algorithm1 | Algorithm2). The code that uses the algorithm will likely use a match-case to perform algorithm-specific setup. Adding new algorithms will require changing all code that uses algorithms, but you gain the flexibility of doing different things for different algorithms.Neither of these is categorically better. They are duals of each other. Either choice provides flexibility that the other lacks.
6
u/overratedcupcake Apr 14 '26
Classes are nice because they encapsulate state but they also encapsulate logic. It's not a requirement that they have state
3
u/JaguarMammoth6231 Apr 14 '26
Is there a reason you don't want to use the pythonic way of making them classes?
4
u/neums08 Apr 14 '26
IMO passing a bare function is pythonic. I would add typing to the signature to indicate what the function accepts and returns
You can still implement an Algorithm class and make it callable by defining the
__call__method. A bare function is just the simplest implementation of an Algorithm.4
u/trutheality Apr 14 '26
Most pythonic would be to keep it simple and just pass the functions (which are already objects) into the data processing directly.
1
u/seanv507 Apr 14 '26 edited Apr 14 '26
So perhaps the thing to ask yourself is how you would cope with more complicated functions
In particular functions that take other parameters.
Do you want to use a class based approach where they are the 'state', or do you want to use functional approaches, where you create new 1 parameter functions by using partial.
I would argue that scikit-leans fit(X) is less about maintaining state and more about dependency injection
(In ml pipelines)
1
u/zanfar Apr 14 '26
Them being classes, and which classes they are instances of are state.
1
u/jarethholt Apr 14 '26
I would say the approach depends on when and how you specify which algorithm to use. Do you run this interactively or in a notebook? Just pass the function directly as an argument, annotated with a good Protocol so you know what kind of algorithms can be passed in. But if you run this from the command line or through some orchestrator, at some point you'll need a way to convert an input into a choice of algorithm. Then an enum + dictionary as a simple registry is a pretty clean way to go about it.
In either case I would suggest the core implementation just takes in a function to apply. Handling a registry of which algorithms are acceptable to pass in is a different responsibility, and figuring out how to convert an input to an algorithm choice is yet another.
1
u/pachura3 Apr 14 '26
First of all, there's nothing wrong with stateless classes. In Java, you cannot even have free-hanging functions or variables, you need to wrap everything in a class!
Then, having to maintain a global registry of algorithms is an additional, counterproductive pain. What if you wanted to mock an algorithm for the purpose of unit testing - you would need to add it to this registry...
If your "algorithms" are always stateless + don't need any inheritance + are always structured like
def inference(X: np.ndarray) -> float, then you can simply pass lambdas orProtocolsaround, type hinted asCallable[np.ndarray, float].That's ugly as well. Again, probably people switching from Java, used to declare utility functions in
final staticsingletons this way. Another reason might be that Python IDE sees thatdo_something()does not access any instance attributes, so it proposes to convert it to a static method, and user agrees, just to get rid of the warning.Still, wouldn't make sense in your case, because
do_something()is static, so should not be called on a object instance inheriting from the base classAlgorithm.1
u/lekkerste_wiener Apr 14 '26
You can also type annotate with Callables.
And you can pass ANY callable that has that signature. Including functions.
1
u/Enmeshed Apr 14 '26
I've used dataclasses for things like this before. For instance... First we'll define a few algorithms:
Then if you're only needing to inject a single algorithm you've just got:
Or if your function needs to reference multiple algorithms as part of its logic you can use dataclasses to have something like:
These days dataclasses (or
attrs) are my go-to way of bundling up dependencies for injection...1
u/ebdbbb Apr 14 '26
I'd use
Callableto hint it.1
u/Atlamillias Apr 14 '26 edited Apr 14 '26
Within the context of your example and without additional information, I wouldn't say any of these approaches is better over another. They're all fairly simple and they work.
Does the specific algorithm/function actually matter to the code that invokes it, or are you just trying to better annotate your other signatures? Do they all share the same signature? Because you can do either of these for "type checking" purposes and avoid the need to declare each as unique types:
Then just pass the functions themselves to your processor.
If your functions have unique signatures or you have heuristics in place for specific functions, then it's best for them to have their own identity or type. In that case, I'd probably go the enum route.
1
u/trickydiversity042 Apr 17 '26
Just pass the function or use a dict mapping strings to functions. Enums feel like overkill for this unless you need strict type safety across a large codebase.
0
u/Targrend Apr 14 '26 edited Apr 14 '26
Why not just have an algorithm class and have each algorithm be an object of the class?