BeeOnRope
BeeOnRope

Reputation: 65056

Conditionally adapt a function of one argument to take two

At some point I have a user-supplied function which either takes 1 or 2 arguments. I want to call it with two arguments, and in the case it only takes one, the second argument should be ignored.

How can I conditionally adapt this function, or otherwise call it so that the unexpected second argument is simply dropped?

def call(f):
    # f might take 1 or 2 arguments, if it takes 2 I should call it like
    f(1, 2)
    # otherwise it should be called like
    f(1)

Is there some way better than explicitly examining the number of arguments e.g., with signature?

Upvotes: 0

Views: 124

Answers (2)

Girardi
Girardi

Reputation: 2809

The only work around I see here is using try/except to catch a TypeError that is raised by a call with the wrong number of arguments.

If you are concerned with performance, be aware that this solution is very inefficient... Probably you should overload the parent ("wrapper") function that would be calling call, such that the parent function already knows whether to call f with 1 or 2 arguments

def call(f):
    try:
        # f might take 1 or 2 arguments, if it takes 2 I should call it like
        f(1, 2)
    except TypeError:
        # otherwise it should be called like
        f(1)

Upvotes: 1

eemz
eemz

Reputation: 1211

Try calling it with two, catch the exception that occurs if it doesn’t take two, call it with one in the except clause.

Upvotes: 0

Related Questions