Home > database >  Python - Passing a function with multiple arguments into another function
Python - Passing a function with multiple arguments into another function

Time:12-02

I have this method that I want to pass into another function.

def get_service_enums(context, enum):
   svc = Service(context)
   return svc.get_enum(enum)

I want to pass this function is as a parameter to another class.

ColumnDef(enum_values=my_func)

Ideally, my_func is get_service_enums. However get_service_enums has a second parameter, enum that I want to pass in at same time I pass in get_service_enums. How can I do this without actually invoking get_service_enums with parenthesis?

CodePudding user response:

using partial from functools to create a new function that only takes the first argument.

from functools import partial

def get_service_enums(context, enum):
    print(context, enum)

partial_function = partial(get_service_enums, enum="second_thing")
partial_function("first_thing")
first_thing second_thing

CodePudding user response:

Does it not work for you to pass the function and its argument separately

ColumnDef(enum_values=get_service_enums, enum)

with the class ColumnDef in charge of passing in enum when the function is invoked?

If not, functools.partial is your friend:

import functools

# New version of get_service_enums with enum = 42
my_func = functools.partial(get_service_enums, enum=42)
my_func('hello')  # hello, 42

ColumnDef(enum_values=my_func)
  • Related