Dynamic/runtime method creation (code generation) in Python

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

    Function docstrings and names are mutable properties. You can do anything you want in the inner function, or even have multiple versions of the inner function that makedynamo() chooses between. No need to build any code out of strings.

    Here's a snippet out of the interpreter:

    >>> def makedynamo(i):
    ...     def innerdynamo():
    ...         print "in dynamo %d" % i
    ...     innerdynamo.__doc__ = "docstring for dynamo%d" % i
    ...     innerdynamo.__name__ = "dynamo%d" % i
    ...     return innerdynamo
    
    >>> dynamo10 = makedynamo(10)
    >>> help(dynamo10)
    Help on function dynamo10 in module __main__:
    
    dynamo10()
        docstring for dynamo10
    

提交回复
热议问题