How can I make the default value of an argument depend on another argument (in Python)?

前端 未结 4 437
庸人自扰
庸人自扰 2020-12-06 00:52

For instance, I want:

def func(n=5.0,delta=n/10):

If the user has specified a delta, use it. If not, use a value that depends on n. Is this

4条回答
  •  情话喂你
    2020-12-06 01:15

    These answers will work in some cases, but if your dependent argument (delta) is a list or any iterable data type, the line

        if delta is None:
    

    will throw the error

    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

    If your dependent argument is a dataframe, list, Series, etc, the following lines of code will work better. See this post for the idea / more details.

        def f(n, delta = None):
            if delta is f.__defaults__[0]:
                delta = n/10
    

提交回复
热议问题