mardi 17 décembre 2019

What's the cleanest and most readable way to ask for user input from 3 available options in a function?

Let's just say I have a function like this:

def make_update(key, val):
   ...

and I want the user to select one of three modes (update or insert, insert but don't update, overwrite and delete existing)

What's the best way to ask for that from the user? If it was just two modes, then we might just be able to have an optional boolean argument.

Two options I thought of:

option 1

def make_update(key, val, upsert=False, set_default=False):
    if upsert:
        do_upsert()
    elif set_default:
        do_set_default()
    else:
        do_override()

which upfront has the downside of an implied but non-explicit ordering of the arguments, where it's not really possible to communicate that those booleans are not mutually exclusive.

I do like, however, that each option (with exception of default override) has an explicit kwarg reference, which makes it simple to call the method like make_update("key", "val", upsert=True).

option 2

def make_update(key, val, mode):
    if mode == "upsert":
        do_upsert()
    elif mode == "set_update":
        do_set_update()
    elif mode == "override":
        do_override()
    else:
        raise ValueError()

which conversely makes it very clear that all three options are not mutually exclusive, but has the downside(?) of not having explicitly defined arguments (think ctrl+space) that the user has to go to documentation for.

This is probably a no brainer but I just wanted to see if there was anything I was overlooking.

Aucun commentaire:

Enregistrer un commentaire