0

I have a project in which I need to do some things, call one of a few functions, and then do some other things:

def doCommand(function, parameter_for_function):
  # do a thing
  function(parameter_for_function)
  # do a thing

My problem is that I don't know if the function I will be passing will require a parameter of its own!

How can I allow my function to call both functions that have no parameters, and functions that have one?

John Ingram
  • 164
  • 1
  • 12
  • You can introspect the function's signature as shown in https://stackoverflow.com/q/847936/3001761 to determine whether it needs the parameter or not. – jonrsharpe Jun 02 '21 at 20:56

2 Answers2

1

The preferred method of handling this is probably along these lines:

def doCommand(function, *args, **kwargs):
  # do a thing
  function(*args, **kwargs)
  # do a thing

*args and **kwargs allow arbitrary arguments to be passed along to a method. As the name implies, these allow you to call doCommand with an arbitrary number of arguments and keyword arguments as well that get passed onto function.

M Z
  • 4,571
  • 2
  • 13
  • 27
0

I suggest explicitly saying that the function you take is one that's called with no parameters:

from typing import Callable

def doCommand(function: Callable[[], None]) -> None:
    # do a thing
    function()
    # do a thing

If the function needs parameters, it's then explicitly the responsibility of the doCommand caller to provide them, e.g. within a lambda expression:

def foo(param) -> None:
    print("foo: ", param)

doCommand(lambda: foo("bar"))

or a named wrapper function:

def foobar() -> None:
    foo("bar")

doCommand(foobar)
Samwise
  • 68,105
  • 3
  • 30
  • 44