Best Way To Create Python Function With Multiple Options?
I've defined a bunch of custom functions and find a lot of them include some identical or similar blocks of code (e.g. just including slightly different strings or arguments). So s
Solution 1:
At the risk of over-engineering your problem, you may use an abstract class and force child to specialize the parts of your procedure. This is possible using the abc
library in Python.
from abc import ABC, abstractmethod
classAbstractProcessor(ABC):
defprocess(self):
some_identical_code
self.some_similar_code()
more_identical_code
@abstractmethoddefsome_similar_code(self):
passclassProcessor1(AbstractProcessor):
defsome_similar_code(self):
print("Proc 1")
classProcessor2(AbstractProcessor):
defsome_similar_code(self):
print("Proc 2")
proc1 = Processor1()
proc1.process()
Solution 2:
Abstract!
- identical code should be a function;
- similar code should be a function with a parameter;
- unique code should be one function for each;
- object oriented code can help here.
To get the idea:
defidentical_code():
lorem ipsum
defsimilar_code(parameter):
lorem ipsum
classBase:def__call__(self, a, b, c):
identical_code()
similar_code(self.parameter())
unique_code()
defunique_code(self):
NotImplemented
defparameter(self):
NotImplemented
classFunc_1(Base):defunique_code(self):
do_it_1()
defparameter(self):
return1classFunc_2(Base):defunique_code(self):
do_it_2()
defparameter(self):
return2
You can then call Func1()(a, b, c)
or Func_2()(a, b, c)
.
Here the NotImplemented
methods are there to show that the base class is just there to define the common behavior, but can't really do anything if you don't specify those two methods.
Some maybe more pythonic way would be to just duck type and remove inheritance:
deffunc(a, b, c, setting):
identical_code()
similar_code(setting.parameter())
setting.unique_code()
classFunc_1:defunique_code(self):
do_it_1()
defparameter(self):
return1classFunc_2:defunique_code(self):
do_it_2()
defparameter(self):
return2deffunc1(a, b, c):
return func(a, b, c, Func_1)
deffunc2(a, b, c):
return func(a, b, c, Func_2)
Solution 3:
Use a function to generate functions from the shared code. Say part of your shared code adds a constant to a value that's passed in:
defadder(n):
defaddTo(x):
return x + n
return addTo
Then, you need an adder that adds 2 and one that adds 4:
add2 = adder(2)
print(add2(2)) # Prints 4
add4 = adder(4)
print(add4(2)) # Prints 6
Post a Comment for "Best Way To Create Python Function With Multiple Options?"