Dynamic/runtime method creation (code generation) in Python

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

    A bit more general solution:

    You can call any method of an instance of class Dummy. The docstring is generated based on the methods name. The handling of any input arguments is demonstrated, by just returning them.

    Code

    class Dummy(object):
    
        def _mirror(self, method, *args, **kwargs):
            """doc _mirror"""
            return args, kwargs
    
        def __getattr__(self, method):
            "doc __getattr__"
    
            def tmp(*args, **kwargs):
                """doc tmp"""
                return self._mirror(method, *args, **kwargs)
            tmp.__doc__ = (
                    'generated docstring, access by {:}.__doc__'
                    .format(method))
            return tmp
    
    d = Dummy()    
    print(d.test2('asd', level=0), d.test.__doc__)
    print(d.whatever_method(7, 99, par=None), d.whatever_method.__doc__)
    

    Output

    (('asd',), {'level': 0}) generated docstring, access by test.__doc__
    ((7, 99), {'par': None}) generated docstring, access by whatever_method.__doc__
    

提交回复
热议问题