Python function that takes one compulsory argument from two choices

后端 未结 3 1349
Happy的楠姐
Happy的楠姐 2021-01-18 16:38

I have a function:

def delete(title=None, pageid=None):
    # Deletes the page given, either by its title or ID
    ...
    pass

However, m

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-18 17:15

    If both arguments can have any value, including None, then the solution is to use a sentinel object for them. Then you can calculate a sum over the number of arguments that are set to non-default value:

    NOT_SET = object()
    def delete(title=NOT_SET, pageid=NOT_SET):
        if sum(i is not NOT_SET for i in [title, page_id]) != 1:
            raise ValueError('Can set only one of these')
    

    This pattern is easily expandable to more arguments as well.

提交回复
热议问题