Python function that takes one compulsory argument from two choices

后端 未结 3 1352
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: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.

提交回复
热议问题