What is the proper way in Python to allow the user to extend the types on which a function can operate without altering the original code of the function?
Suppose I have a module with a my_module.foo()
function that was originally written to work on float
types. Now I would like the same function to be able to work also with, let's say, mpmath
arbitrary precision floats - but without altering the code in the original module.
In C++ I would add an extra overload (or, more likely, some template specialisation trickery with an helper struct). How should I structure the original my_module.foo()
code so that the user can add her own custom hooks inside?
I can think of a few way to achieve this, but as a novice Python programmer I am sure most of them are going to be horrid :)
EDIT: thanks for all the answers so far, much appreciated.
I should probably clarify that one key requirement is being able to cope with types which I have not defined myself. E.g., if I am trying to code a generic cos
function in my module, I want to call math.cos
on builtin types, mpmath.cos
on mpf
types, sympy.cos
on sympy symbolic types, etc. And of course I would like the dispatching logic not to be in my module's cos
implementation.