Python function that takes one compulsory argument from two choices

痞子三分冷 提交于 2020-11-29 07:27:44

问题


I have a function:

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

However, my intention is for the function to take only one argument (either title OR pageid). For example, delete(title="MyPage") or delete(pageid=53342) are valid, while delete(title="MyPage", pageid=53342), is not. Zero arguments can not be passed. How would I go about doing this?


回答1:


There is no Python syntax that'll let you define exclusive-or arguments, no. You'd have to explicitly raise an exception is both or none are specified:

if (title and pageid) or not (title or pageid):
    raise ValueError('Can only delete by title OR pageid')



回答2:


I don't think there's any way to do this in the function signature itself. However, you could always have a check inside your function to see if both arguments are set

def delete(title=None, pageid=None):
# Deletes the page given, either by its title or ID
    if title and pageid:
        # throw error or return an error value
pass

Arguably a better way of doing it would be to define 2 methods that call the delete method

def delete_by_title(title):
    delete(title=title)

def delete_by_id(id):
    delete(pageid=id)

The second method won't stop people calling the delete function directly, so if that's really important to you I'd advise having it throw an exception as per my first example, or else a combination of the 2.




回答3:


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.



来源:https://stackoverflow.com/questions/39189472/python-function-that-takes-one-compulsory-argument-from-two-choices

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