Dynamic/runtime method creation (code generation) in Python

后端 未结 6 1425
死守一世寂寞
死守一世寂寞 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:10

    class Dynamo(object):
        def __init__(self):
            pass
    
        @staticmethod
        def init(initData=None):
            if initData is not None:
                dynamo= Dynamo()
                for name, value in initData.items():
                    code = '''
    def %s(self, *args, **kwargs):
    %s
                                ''' % (name, value)
                    result = {}
                    exec code.strip() in result
                    setattr(dynamo.__class__, name, result[name])
    
                return dynamo
    
            return None
    
    service = Dynamo.init({'fnc1':'pass'})
    service.fnc1()
    

提交回复
热议问题