簡體   English   中英

是否可以在運行時生成帶參數的Python函數?

[英]Is it possible to generate a Python function with arguments in runtime?

說,

我有一個python函數如下:

def ooxx(**kwargs):
    doSomething()
    for something in cool:
        yield something

我想為提示提供另一個帶有命名參數的函數,如下所示:

def asdf(arg1, arg2, arg3=1):
    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)
    kwargs = dict((key, values[key]) for key in args) # convert args list into dictionary form
    return list(ooxx(**kwargs))

是否有可能使用某種方法自動生成“asdf”函數? 我有很多動態生成的ooxx函數,我希望有相應的asdf函數和自定義的命名參數。 不確定這是正確的要求還是正確的編碼方式:p

你的描述對我來說沒有意義:你寫了一個非常詳細的函數來做到這一點:

def asdf(arg1, arg2, arg3=1):
    return list(ooxx(**locals()))

但你想檢查ooxx並以某種方式為asdf的參數組成適當的名稱? 這是不可能的, ooxx上沒有關於此的信息。

如果你實際上一個簽名並想要從中創建一個函數,你將不得不求助於eval或生成Python文件的函數定義並導入它。

還有裝飾模塊。 您可以像這樣創建一個函數:

import decorator
asdf = decorator.FunctionMaker.create(
                'asdf(arg1, arg2, arg3)', # signature
                'return ooxx(**locals())', # function body
                {'ooxx' : ooxx}, # context for the function
                ('arg3', 1)) # default arguments

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM