I have two files in a library I am creating:
file1.py
def func1(a, b):
c = a + b
return c
file2.py
def func2(a, b):
c = a - b
return c
Now I want each file to have a function that takes the function from that file as an argument, but otherwise does the same thing. So a function like:
def new_func(f, x, y, z):
return f(x, y) * z
Since I don't want to repeat myself, I would prefer to define this function in a separate file, then use some sort of function inheritance that creates a partial function with the first argument set to the func at the beginning of that file. So users can access new_func
using file1.new_func(x, y, z)
and file2.new_func(x, y, z)
.
For context, I have many new_func
s I want to add to about a handful of files. Each would take in the func at the beginning of the file as a fixed argument, so essentially a partial function. But beyond that, they would all do the same thing with that func.
Is this possible using the functional programming paradigm?
I have Googled like crazy about function inheritance, partial functions and decorators (as I thought that might help), but have so far found nothing like what I am attempting to do.
EDIT: To be clear, the point of this question is (1) multiple files each with a single function and (2) a set of partial functions that would take in the single function as the fixed parameter, but without copying and pasting the partial functions to each file. That is why I mention inheritance, as I essentially want to do some sort of function inheritance rather than copying and pasting functions across files.
Your question asks to mix two things (inheritance and partial function binding) together that are both possible to do separately, but not really something that can happen automatically together.
In Python inheritance is strictly a thing for classes. You're not using classes, but if you did, you could get a base class new_function
to call different function1
methods on its subclasses:
class BaseClass:
def base_function(self, a, b, c):
return self.child_function(a, b) * c
class File1Class(BaseClass):
def child_function(self, a, b):
return a+b
class File2Class(BaseClass):
def child_function(self, a, b):
return a-b
f1c = File1Class()
f2c = File2Class()
print(f1c.base_function(1, 2, 3)) # prints 9
print(f2c.base_function(1, 2, 3)) # prints -3
If you don't want to use classes, you can partially bind functions to do what you want, but it won't happen automatically, since you don't have any inheritance hierarchy. You'll need to do the partial binding yourself:
def function1(a, b):
return a+b
def function2(a, b):
return a-b
def new_function(f, a, b, c):
return f(a, b)*c
from functools import partial
new_function1 = partial(new_function, function1)
new_function2 = partial(new_function, function2)
print(new_function1(1, 2, 3)) # prints 9
print(new_function2(1, 2, 3)) # prints -3