Python Coding Style – Call Sub Function Based on Variable Value

coding-stylepython

I have a function containing other functions. These function are called based on value of variable action.

These sub functions are logically grouped – i.e., they all deal with file manipulation.

Each function has 2 to 5 lines.

I would like to improve the style.

Is there a more concise way of achieving this end than what I have below? I feed there is a log of defining functions that contain not many LOC.

def my_function(action):

    return { '1': func_a, '2': func_b, '3': func_c, '4': func_d}.get(action, err)()

    def func_a():
        ...
        ...
        return ...
    def func_b():
        ...
        ...
        ...
        return ...
    def func_c():
        ...
        ...
        return ...
    def func_d():
        ...
        ...
        return ...
    def err():
        return

*discaimer: actual functions have logical names.

My issue is with the proliferation of functions to define

Best Answer

If you cannot factor out common code in these functions they may not be reduced in size, if you cannot factor out features into common feature paths they cannot be reduced in number.

That said this approach is marvelous in my opinion and I have used dictionaries of functions to great effect in the past.

I can give one suggestion to your approach: Don't nest all the functions inside of the dispatching function. This may alleviate some of your concerns of cleanliness, perhaps something like:

def my_function(action):
    return { '1': func_a, '2': func_b, '3': func_c, '4': func_d}.get(action, err)()

def func_a():
    ...
    ...
    return ...
def func_b():
    ...
    ...
    ...
    return ...

By having separate functions which return the dispatchable functions, you can effectively move those functions to wherever they best fit in your system hierarchy, and your dispatcher simply calls them out. However if the nesting approach is the best modeling given your system then stick with what you have.

Related Topic