0

The question is pretty much self contained. I have a function with some default parameters, for example

def f(x=None):
    # some code...

defined in a module. I want to be able to import this function in a script and depending an some values computed in this script modify the default values to have effectively:

def f(x=0):
    # same code as before

How can I do that? (I know they are plenty of ways to do almost the same thing like defining a new function based on f, but I really want to modify f itself if possible.)

Julien
  • 13,986
  • 5
  • 29
  • 53
  • Is this because you want to "hack" a 3rd party library you have no direct access to, or because you think this is a good design pattern? – deceze Aug 01 '16 at 13:02
  • @deceze the latter one, but more because I can't think of a more convenient way to get what I want. The script in question is to be used interactively... I guess I could use my own suggestion, but I'm curious if what I want is possible) – Julien Aug 01 '16 at 13:04
  • The function should simply read its default value from somewhere, e.g. inside the function you do `x = x or mymodule.mydefault`. You can then indirectly set `mymodule.mydefault` which the function will pick up if `x` is `None`. – deceze Aug 01 '16 at 13:06
  • 1
    "I know they are plenty of ways to do almost the same thing like defining a new function based on `f`" I think you answered your question yourself, the most appropriate way (and by far the best design pattern) is to do exactly this – Sander Aug 01 '16 at 13:08
  • @deceze Actually this sounds even better since I would want to change the default value of several functions in the module at once. However the exact implementation you suggest is not too clear to me, could you write an quick example please? – Julien Aug 01 '16 at 13:10

0 Answers0