Setting the default value of a function input to equal another input in Python

喜你入骨 提交于 2019-12-03 11:04:07

问题


Consider the following function, which does not work in Python, but I will use to explain what I need to do.

def exampleFunction(a, b, c = a):
    ...function body...

That is I want to assign to variable c the same value that variable a would take, unless an alternative value is specified. The above code does not work in python. Is there a way to do this?

Thank you.


回答1:


def example(a, b, c=None):
    if c is None:
        c = a
    ...

The default value for the keyword argument can't be a variable (if it is, it's converted to a fixed value when the function is defined.) Commonly used to pass arguments to a main function:

def main(argv=None):
    if argv is None:
        argv = sys.argv

If None could be a valid value, the solution is to either use *args/**kwargs magic as in carl's answer, or use a sentinel object. Libraries that do this include attrs and Marshmallow, and in my opinion it's much cleaner and likely faster.

missing = object()

def example(a, b, c=missing):
    if c is missing:
        c = a
    ...

The only way for c is missing to be true is for c to be exactly that dummy object you created there.




回答2:


This general pattern is probably the best and most readable:

def exampleFunction(a, b, c = None):
    if c is None:
        c = a
    ...

You have to be careful that None is not a valid state for c.

If you want to support 'None' values, you can do something like this:

def example(a, b, *args, **kwargs):
    if 'c' in kwargs:
        c = kwargs['c']
    elif len(args) > 0:
        c = args[0]
    else:
        c = a



回答3:


One approach is something like:

def foo(a, b, c=None):
    c = a if c is None else c
    # do something


来源:https://stackoverflow.com/questions/3534371/setting-the-default-value-of-a-function-input-to-equal-another-input-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!