Python dynamic function creation with custom names

后端 未结 6 2334
深忆病人
深忆病人 2020-11-27 18:07

Apologies if this question has already been raised and answered. What I need to do is very simple in concept, but unfortunately I have not been able to find an answer for it

6条回答
  •  青春惊慌失措
    2020-11-27 19:04

    There probably is a sort of introspection to do this kind of thing, but I don't think it would be the pythonic approach to the problem.

    I think you should take advantage of the nature of functions in python as first level citizens. Use closures as Shane Holloway pointed, to customize the function contents as you like. Then for the dynamic name binding, use a dictionary whose keys are the names defined dynamically, and the values will be the functions itself.

    def function_builder(args):
        def function(more_args):
           #do stuff based on the values of args
        return function
    
    my_dynamic_functions = {}
    my_dynamic_functions[dynamic_name] = function_builder(some_dynamic_args)
    
    #then use it somewhere else
    my_dynamic_functions[dynamic_name](the_args)
    

    Hope it makes sense to your use case.

提交回复
热议问题