Dynamic/runtime method creation (code generation) in Python

后端 未结 6 1402
死守一世寂寞
死守一世寂寞 2020-11-28 03:45

I need to generate code for a method at runtime. It\'s important to be able to run arbitrary code and have a docstring.

I came up with a solution combining exe

6条回答
  •  醉梦人生
    2020-11-28 04:09

    Python will let you declare a function in a function, so you don't have to do the exec trickery.

    def __init__(self):
    
        def dynamo(self, arg):
            """ dynamo's a dynamic method!
            """
            self.weight += 1
            return arg * self.weight
        self.weight = 50
    
        setattr(self.__class__, 'dynamo', dynamo)
    

    If you want to have several versions of the function, you can put all of this in a loop and vary what you name them in the setattr function:

    def __init__(self):
    
        for i in range(0,10):
    
            def dynamo(self, arg, i=i):
                """ dynamo's a dynamic method!
                """
                self.weight += i
                return arg * self.weight
    
            setattr(self.__class__, 'dynamo_'+i, dynamo)
            self.weight = 50
    

    (I know this isn't great code, but it gets the point across). As far as setting the docstring, I know that's possible but I'd have to look it up in the documentation.

    Edit: You can set the docstring via dynamo.__doc__, so you could do something like this in your loop body:

    dynamo.__doc__ = "Adds %s to the weight" % i
    

    Another Edit: With help from @eliben and @bobince, the closure problem should be solved.

提交回复
热议问题