Call function without optional arguments if they are None

前端 未结 9 2075
自闭症患者
自闭症患者 2020-12-29 02:00

There\'s a function which takes optional arguments.

def alpha(p1=\"foo\", p2=\"bar\"):
     print(\'{0},{1}\'.format(p1, p2))

Let me iterat

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 02:09

    Unfortunately, there's no way to do what you want. Even widely adopted python libraries/frameworks use your first approach. It's an extra line of code, but it is quite readable.

    Do not use the alpha("FOO", myp2 or "bar") approach, because, as you mention yourself, it creates a terrible kind of coupling, since it requires the caller to know details about the function.

    Regarding work-arounds: you could make a decorator for you function (using the inspect module), which checks the arguments passed to it. If one of them is None, it replaces the value with its own default value.

提交回复
热议问题