0

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?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

for your first suggestion, if ColumnDef has multiple constructor arguments would the syntax look like ColumnDef(name='A', data_type='B', enum_values=(get_service_enums, enum), db_col_name='D') ? I wasn't aware that python allows you to pass in a function and its argument separately.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.