Python nested functions best practice

  oop, python

I am writing a module to translate pandas code to SQL. The problem I am facing, is that I have multiple functions that are only called inside other functions.The inner functions were created to make the code more readable and avoid repeating the same code. Should I make them nested, for the code to be more readable? And should I always make as many functions as possible nested, if they aren’t used somewhere else? What about ‘function bloat’? What do you guys prefer?

The functions are:

(1) def convert_series(self, code, library_context, code_reference) 
    -> 5 lines of code
    -> Wraps the call of the recursive helper function (2) in a "WITH ... AS" block
    -> entry-point for the user of the module

(2) def _convert_series_operations_recursive(self, node, library_context)
    -> recursively translates the statement to SQL
    -> 40 lines of code
    -> ONLY used inside of (1)

(3) def _convert_bin_op(self, node, library_context)
    -> 30 lines
    -> ONLY used inside of (2)

(4) def _convert_bin_op_handle_sides(self, node, library_context)
    -> 13 lines
    -> ONLY used inside of (2)

The structure I would prefer is to put the functions (2), (3), (4) inside (1). Would this be the best solution? The other option is to put them inside the class along with (1).

Keep in mind that (2), (3), (4) are called often, so the only way of nesting would be to put them in (1) to avoid redefining them in each recursive call.

Source: Python Questions

LEAVE A COMMENT