sten
sten

Reputation: 7476

Dynamic function signature based on available args?

I want to call function with dynamic signature based on what arg I have instantiated. The basic logic is:

if args is None and kwargs is None : return fun()
if args is not None and kwargs is None : return fun(*args)
if args is None and kwargs is not None : return fun(**kwargs)
if args is not None and kwargs is not None : return fun(*args,**kwargs)

Is there a shortcut way to do this?

The process is __call__ stores the arguments, which are reused during op overloading __rmod__, which calls a wrapper around fun().

The idea is to rework:

data % fun(args,kw) % .....

to:

fun(data,args,kw) % ......

Plus special handling when data is list-like structure; that's why a wrapper around fun() is needed.

Upvotes: 0

Views: 55

Answers (2)

John Kugelman
John Kugelman

Reputation: 361645

Instead of setting them to None when empty, set args to an empty list and kwargs to an empty dict. Then you can just write func(*args, **kwargs) without worrying about whether they're set or not.

args = []
kwargs = {}
return func(*args, **kwargs)

Upvotes: 2

Reznik
Reznik

Reputation: 2806

You can just pass it as:

return func(*args, **kwargs)

It is not a syntax erorr

lets say args = []

print(*args) will print nothing, it is not like args will contains a None

Upvotes: 2

Related Questions