Python: How to pass arguments to the __code__ of a function?

前端 未结 6 459
别那么骄傲
别那么骄傲 2020-12-02 20:55

The following works:

def spam():
    print \"spam\"
exec(spam.__code__)

spam

But what if spam

6条回答
  •  天命终不由人
    2020-12-02 21:25

    I think there are probably some design considerations in your larger application that could make you not care about this problem, like perhaps having some collection of 'known good and valid' functions distributed as a module that the executing agents know about or something.

    That said, one hacky solution would be:

    >>> def spam(eggs):
    ...     print "spam and %s" % eggs
    ...     
    ... 
    >>> spam('bacon')
    spam and bacon
    >>> def util():
    ...     pass
    ...     
    ... 
    >>> util.__code__ = spam.__code__
    >>> util('bacon')
    spam and bacon
    >>> 
    

提交回复
热议问题