簡體   English   中英

一個返回多個函數的裝飾器

[英]A decorator that returns multiple functions

我想編寫一個裝飾器,將多個函數放入模塊命名空間。 考慮以下模塊:

# my_module.py


from scipy import signal


@desired_decorator(new_size=(8, 16, 32))
def resample(x, new_size):
    return signal.resample(x, new_size)

我現在想要從my_module導入resample_8resample_16resample_32 我可以編寫裝飾器並讓它返回一個函數列表,但是如何在模塊命名空間中提供這些函數呢?

由於您可以在不使用偷偷摸摸的黑客的情況下分配到全局字典,這幾乎是可能的。 (語法很好)

編輯:K,也許這是一個位鬼鬼祟祟的。 如果沒有監督Pythonista,請不要在家里試試。 馬蒂諾

EDIT2:可以通過使用堆棧內省來獲取調用者的全局變量,這可以避免導入問題,但是當在非全局命名空間中調用時,它將無法工作,或者在6個月內消除您的混淆。 user2357112

globals()返回全局變量的字典。 分配給此用戶可以導入這些功能

functools.partial是制作部分功能的好方法。 這基本上是一個“半完成”的函數調用。 創建部分函數使其記住參數和關鍵字參數,並調用該部分函數將使用參數和關鍵字參數調用原始函數。 在這里閱讀更多相關信息。

這是你想要的裝飾器,但我強烈建議不要使用它。

from functools import partial

def desired_decorator(**kwargs):
    # make sure there's only one keyword argument
    assert len(kwargs) == 1
    # unpack the single keyword and the values
    keyword, values = (*kwargs.items(),)[0]
    # this is the actual decorator that gets called
    def _make_variants(func):
        for value in values:
            # assign to the globals dictionary
            globals()[
                f"{func.__name__}_{value}"
            ] = partial(func, **{keyword: value})
        # keep the original function available
        return func
    return _make_variants

我的另一種選擇是使用Chris所說的,因為從裝飾器創建許多函數不利於維護和清晰。

這是我建議的代碼,但如果你願意,可以使用上面的代碼。

from functools import partial

# assign your function things here
resample_8 = partial(resample, new_size=8)
# repeat for other names

暫無
暫無

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

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