1

Trying to validate function parameter combinations. Such that (), (project), (project,field) and (project,field,well) are valid and every other combination (e.g. (field)) is not. If available, arguments will be strings otherwise defaults are None or empty string "". Currently doing poor man's bit mask check...

def make_thing(project=None, field=None, well=None):
    # check for valid p-f-w combinations
    check = (8 if project else 0) + (4 if field else 0) + (1 if well else 0)
    if check not in (0, 8, 8 + 4, 8 + 4 + 1):
        return None

    # continue to do work

Question: What is a proper Pythonic way to do this?

Thank you!

1 Answer 1

1

First Suggestion

def make_thing(project=None, field=None, well=None):
    if (not project and field) or (not field and well):
        return

    # continue to do work

Second Suggestion

def make_thing(project=None, field=None, well=None):
    if (bool(project), bool(field), bool(well)) not in (
        (False, False, False),
        (True, False, False),
        (True, True, False),
        (True, True, True),
    ):
        return

    # continue to do work
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, but this is difficult to reason about.. at least for me.
@k1m190r I guess so. A first suggestion may not be Pythonic. I add a second suggestion.
and to continue the craziness itertools.combinations_with_replacement([True, False], 3) ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.