Search code examples
pythonpython-3.xkeyword-argument

Chaining kwargs in a function call


I have an AND and OR function that evaluates an expression. I would like to chain these items together into something like this:

>>> AND(
        # kwarg
        Neutered=True, 
        # reduces/evaluates to arg/value
        OR(Black=False, AND(Female=False, NOT(White=True)), AND(NOT(Female=False), OR(White=True, Tan=True))))

However, I get this error when doing so:

SyntaxError: positional argument follows keyword argument

This is because the OR evaluates to a boolean and not a kwarg, which is how it needs to be passed. What would be a good way to get around this issue?


Solution

  • Simply rearrange the call to have the kwargs after the args:

    AND(
        OR(AND(NOT(White=True), Female=False), AND(NOT(Female=False), OR(White=True, Tan=True)), Black=False),
        Neutered=True)
    

    Or, if possible, use the dict unpacking operator:

    AND(
        Neutered=True,
        **OR(Black=False, **AND(Female=False, **NOT(White=True)), **AND(NOT(Female=False), OR(White=True, Tan=True))))