Search code examples
pythonparameter-passingkeyword-argument

How to pass kwargs with function calls without immediate execution


I want to pass a dict of function calls with function arguments as kwargs to another function. Unfortunately the passed functions get executed immediately rather than passed as the following example illustrates:

def info(info='NO INFO'):  # just a test function
    print(); print('\'', info, '\'', sep=""); print()

kwargs = {'one': info('executed one'), 'two': info('executed two')}

which results in:

'executed one'


'executed two'

How can I prevent these arguments from being executed and just passed on?


Solution

  • You're not passing a function, you're passing the result of calling the function. Python has to call the function(s) as soon as it reaches that line: kwargs = {'one': info('executed one'), 'two': info('executed two')} in order to know what the values are in the dict (which in this case are both None - clearly not what you intend).

    As I said, you need to pass an actual function, which can be easily done with (for example, there are other ways) lambdas - lambdas with no arguments are not common but are allowed:

    kwargs = {'one': (lambda: info('executed one')), 'two': (lambda: info('executed two'))}