Python function that takes one compulsory argument from two choices

后端 未结 3 1350
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 16:59

    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')
    
    0 讨论(0)
  • 2021-01-18 17:05

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题