user1330974
user1330974

Reputation: 2616

How to call Python partial without using parentheses?

Suppose the code below:

from functools import partial
import random

def integer(min=1, max=10):
    return random.randint(min, max)

def double(min=1, max=10):
    return random.uniform(min, max)

if __name__ == '__main__':
    p1 = partial(integer, 5, 10)
    p2 = partial(double, 5, 10)
    for f in [p1, p2]:
        f() # I'd like to know if there's a different way to call this like `call(f)` or something

As mentioned in the comment, I'd like to know if there's a way to call f without using parentheses. One step further, suppose I can call f without using parentheses, if I would like to pass additional parameters to f, how do I go about it (like call(f, additional_param_1, additional_param_2))?

Thank you in advance for your answers!

Upvotes: 0

Views: 145

Answers (1)

Grismar
Grismar

Reputation: 31319

Not in base Python, but you can easily write call() yourself:

from functools import partial
import random

def integer(min=1, max=10):
    return random.randint(min, max)

def double(min=1, max=10):
    return random.uniform(min, max)

def call(f, *args, **kwargs):
    return f(*args, **kwargs)

if __name__ == '__main__':
    p1 = partial(integer, 5, 10)
    p2 = partial(double, 5, 10)
    for f in [p1, p2]:
        call(f)

Note: you have a typo in your example, you're calling partial on int, but your function is called integer. (neither is a very good name and I think you're trying to solve a problem that you're not stating, that has a better solution)

Upvotes: 1

Related Questions