# Is There Such Thing As Function Inheritance

I know about class inheritance but today I wondered what if there was an easier to create functions that are similar to other functions.
Pretend this:

def add(num1, num2): try: return num1 + num2 except (ValueError, TypeError) as error: print(f"There is an {error.__name__}: {error}") def add_and_mult(num1, num2, num3): try: return add(num1, num2) * num3 finally: except (ValueError, TypeError) as error: print(f"There is an {error.__name__}: {error}") print(add_and_mult(1, 2, 3))

That is what it might look like without function inheritance(probably not real).

With function inheritance:

``````def add(num1, num2):
try:
return num1 + num2

except (ValueError, TypeError) as error:
print(f"There is an {error.__name__}: {error}")

def add_and_mult(num1, num2, num3), (add): # I put , to separate the parameters from the function that the function inherits from and (add) like class inheritance.
try:
return super(num1, num2) * num3

finally:
except (ValueError, TypeError) as error: # Is this valid even though it is not exactly the next command after try?
print(f"There is an {error.__name__}: {error}")

``````

What if function inheritance was real? It makes some functions better.
Also what are the errors that could happen when I’m adding and multiplying? I used ValueError and TypeError. Is it okay to have 2 `try`s, 2 `else`s or 2 `finally`s in a `try``except` clause?

``````>>> def add(a, b):
return a + b

>>> def mul(a, b):
return a * b

27
23
>>> mul(2, mul(3, mul(4, mul(5, mul(6, 7)))))
5040
>>> add(mul('Ho, ', 3), 'Green Giant!')
'Ho, Ho, Ho, Green Giant!'
>>>
``````

Two simple, portable functions that can be combined.

This brings us to exception handling. We can see that the plus sign is also the concatenation operator and that the times sign is also the repeat operator. That means there are multiple valid input types. What are the actual exceptions that could be raised? Can we filter them so exception handling is not necessary?

The most sensible approach is to validate before passing arguments to a function, but that doesn’t really insulate the function, itself. However if we encapsulate a function we can make it inaccessible to outside calls. Obviously, this takes us down another rabbit hole.

2 Likes

How do I encapsulate a function?

What if we make `mul` a higher order function that can take in `add` as an default argument defaults’ value equal to None?

Can you give us an example of what you mean?