Python Pattern best practice

  • Ahoi,

    anyone can tell me if there is a pattern/best practice to handle this type of request handling?

    I am trying to handle the execution of functions by name.

    I found a pattern for classes using a dicitionary but i couldnt make it work like this.

    https://github.com/faif/python-patterns/blob/master/patterns/creational/factory.py

    What i have i have made work is this, i was just wondering if there already is a (THE WAY) way to handle this.

    def func1(p1):
    print(p1)


    def func2(p1, p2):
    print(p1, p2)


    def func_handler(func_name, *args):
    # Get dynamic number of arguments as a single string
    arg_list = list(args)
    arg_list = [str(ele) for ele in arg_list]
    params = ', '.join(arg_list)

    # Execute function + parameters
    eval(func_name + '(' + params + ')')

    func_handler('func1', 1)
    func_handler('func2', 1, 2)

     

  • Thanks for posting your issue and hopefully someone will answer soon.

    This is an automated bump to increase visibility of your question.

  • def func1(p1):
    print(p1)


    def func2(p1, p2):
    print(p1, p2)


    def func_handler(func, *args):
    func(*args)


    func_handler(func1, 1)
    func_handler(func2, 1, 2)

    I'm not sure what you're really after here, but functions are "first class citizens" in Python. Functions are objects, just like other objects, and can be passed around and called (I'd avoid "eval" if you can). The trickiness comes from executing functions with arguments, but a quick Google for "execute function variable with parameters python" gave me lots of results that I think will help you more in that regard.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply