0

I am using a Python library (APScheduler) that requires some function handlers. All these handlers functions are almost the same. The only difference is a "constant" (as in, logic is the same; only the constant used to reference some data structures is different).

I would like to have a single generic function for all the handlers such that I can minimise my code or not having to add new functions when I add new types. Moreover, this enables me to have my types declared in a configuration file.

In Javascript this would be possible like this:

function staticFunction(args) {
    // ... this function I have to parameterise
};

function factory(type) {
    return function(args) {
        // ... this function is parametrised with "type"
    };
}

addHandler(staticFunction)
addHandler(factory("apples"));
addHandler(factory("oranges"));

How do I do the same in Python?

0

1 Answer 1

4

You can do exactly the same thing in Python; you can create a nested function that'll have access to type as a closure:

def factory(type):
    def nested(args):
        # do something with `type`
    return nested

add_handler(factory('apples'))

There are more ways you can bind a parameter to a callable; you could use a lambda to proxy the function call:

def static_function(type, args):
    # ...

add_handler(lambda args: static_function('apples', args))

or you could use a functools.partial() object to bind arguments to a callable:

from functools import partial

add_handler(partial(static_function, 'apples'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.