Search code examples
pythonnested-functionlocals

Pythonic? ...Dynamically calling nested functions


Is this a a pythonic implementation?

I'm calling nested functions dynamically from a string argument with wrappers to reduce the chance of calling a non-existent function. Here's an example where I want to perform different comparisons on arg1 and arg2 (in terms of ==, >=, < etc)...

class ComparisonClass(object):
    def__init__(self):
        pass

    def comparison(self,arg1,arg2,comparison):
        def equal_to():               
            pass
        def greater_than():
            pass
        def less_than():
            pass

        return locals()[comparison]()

    def comparison_equal_to(self,arg1,arg2):
        return self.comparison(arg1,arg2,'equal_to')

    def comparison_greater_than(self,arg1,arg2):
        return self.comparison(arg1,arg2,'greater_than')

    def comparison_less_than(self,arg1,arg2):
        return self.comparison(arg1,arg2,'less_than')

Solution

  • What you're missing is that in Python, functions are first-class objects. That means they can be assigned to variables and passed around just like any other object.

    So, rather than nesting a function and calling it within the parent function, you just want to assign the relevant function as the return value of your function, and call it on return. Or even better, assign a dictionary at class level containing the functions:

    def equal_to():
           pass
    
       (etc)
    
    COMPARISONS = {
        'equal_to': equal_to,
        etc
    }
    

    Now you can call COMPARISONS['equal_to'](arg1, arg2).