Linightz
Linightz

Reputation: 185

Any way to put an if statement in the function call argument?

I found out that we can use the ternary op inside the function call argument:

def foo(n):
    print(n)
a, b = 1, 2
foo(a if a>b else b)
# prints 2

I wonder is there a way to use if without the else in the function call argument? so something like if it's true, pass a to it, if not, don't pass anything.

I've tried

foo(a if a>b else pass)
foo(a if a>b)
foo(if a>b: a)
foo(a>b and a)

None of the above works.

Thanks for your help.

Edit-----

Sorry, let me rephrase my question.

What I'm asking for is a way to determine whether I should pass the argument based on a condition.

So basically I have to call a big function that takes a lot of kwargs, say:

# function call
thefunc(
    a=1,
    b=2,
    c=3,
    d=4,
    e=5
    #...
)

And all of the args are options which its up to me, or in some cases, a condition.

Since the argument list is so big that writing function calls inside the if statement is not preferred, so I need to know is there a way to, say:

thefunc(
    a=1,
    #if condition: b=2,
    c=3,
    ....
)

So to determine whether to give the kwarg or not. Its okay if there isn't, just need to know, thanks.

Upvotes: 6

Views: 11332

Answers (2)

RemcoGerlich
RemcoGerlich

Reputation: 31250

You can if you don't mind some ugliness... The * syntax turns a list of values into parameters, so you could use:

foo(*[a] if a > b else [])

Whether you should is something else :-)

Upvotes: 4

vurmux
vurmux

Reputation: 10020

Ternary operator needs both if- and else- substatements. Instead of trying to use only-if, you can use default function arguments:

def foo(n=None):

Pass None to the function, if needed:

foo(a if a > b else None)

And check inside for the None - non-None argument:

def foo(n=None):
    if n:
        print(n)

Upvotes: 2

Related Questions