0

Here I have an example dictionary of functions:

d = {
    '1' : f
    '2a' : g
    '2b' : h
    '3' : i
    ...
}

Where some functions take no arguments and the rest always take the same arguments a, b.

def f(a, b): ...
def g(): ...
def h(a, b): ...
def i(): ...

How do I call a function from this dictionary with/without arguments depending on if the function takes arguments?

i.e. With an arbitrary key x.

if [d[x] takes arguments]:
    d[x](a, b)
else:
    d[x]()

Note: have to run out for an hour, so won't be able to reply straight away.

4
  • As stated in the linked answer: use the signature function imported from inspect Commented Jul 26, 2017 at 21:46
  • I'd keep it simple in this case without the huge overhead of inspecting functions upfront before calling them. The EAFP approach is more than adequate for this purpose. Commented Jul 26, 2017 at 21:47
  • @zwer I was actually going to suggest that too...but I feel like there is more to check with what kind of TypeError is being raised. e.g. not enough arguments for the function that takes arguments. But for this specific example if it is always contained in that way knowing if it is a function with no arguments or two arguments, it could work I suppose. Commented Jul 26, 2017 at 21:50
  • @zwer Thanks for that suggestion, it ended up working way better that way. Commented Jul 27, 2017 at 6:10

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.