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.

Graviton
  • 371
  • 1
  • 4
  • 14
  • As stated in the linked answer: [use the signature function imported from inspect](https://docs.python.org/3/library/inspect.html#inspect.signature) – agtoever Jul 26 '17 at 21:46
  • I'd keep it simple in this case without the huge overhead of inspecting functions upfront before calling them. The [**EAFP**](https://docs.python.org/2/glossary.html#term-eafp) approach is more than adequate for this purpose. – zwer Jul 26 '17 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. – idjaw Jul 26 '17 at 21:50
  • @zwer Thanks for that suggestion, it ended up working way better that way. – Graviton Jul 27 '17 at 06:10

0 Answers0