簡體   English   中英

使用 Python 類型提示來指定一個類型應該就是那個?

[英]Using Python type hints to specify that a type should be just that?

我可以像這樣使用 Python 的類型系統嗎?

def myFunc(type : type, any):

因此以下是 function 的有效用途。

myFunc(int, 4)
myFunc(float, "abc")
myFunt(myClass, [2, [4, "six"]])

但這不是。

myFunc(2, 3)

如果這是不可能的,我是否可以通過要求 object 具有構造函數或要求類型為 class 或內置類型來實現類似的功能?

def myFunc(type : has(__init__), any):
def myFunc(type : POD or Class, any):

您想要的兩件事都可以通過使用裝飾器來完成。

我可以通過要求 object 具有構造函數或要求類型為 class 或內置類型來實現類似的東西嗎

首先定義一個裝飾器(一個 function 做你想做的事,讓你處理 arguments 或在調用之前用 function 做任何你想做的事情)

def decorator(function):
    def wrapper(*args, **kwargs): # the function that does the checks
        # you can do the same for any keyword arguments
        for argument in args:
            if hasattr(argument, "__init__"): 
                print(f'Argument {argument} has an __init__ method')
        return function(*args, **kwargs)
    return wrapper

然后你可以將它應用到任何 function

@decorator
def myFunction(some_argument):
    return None

例如,如果您使用int調用myFunction ,您將獲得以下信息

In [18]: myFunction(3)
Argument 3 has an __init__ method

我可以像這樣使用 Python 的類型系統嗎? ... 這樣以下是 function 的有效用途。

您可以在裝飾器內部檢查__anotations__的 __annotations__ ,如問題所述,並驗證每個輸入。 __anotations__返回一個字典,用鍵指定變量的名稱和值的類型注釋。 一個簡單的例子是

def decorator(function):
    def wrapper(*args, **kwargs):
        # {'a': <class 'str'>, 'b': <class 'int'>}
        type_hints = function.__annotations__ 
        
        # kwargs is a dictionary so
        # if a and b are parameters whose values are hello and
        # 2 then the dict is {a: "hello", b: 2}
        for keyword in kwargs:
            assert type(kwargs.get(keyword)) == type_hints.get(keyword)

        # also check on the list args
        for index, argument in enumerate(args):
            assert type(argument) == type_hints[list(type_hints)[index]]

        return function(*args, **kwargs)
    return wrapper

@decorator
def myFunc(a: str, b: int):
    return a, b

現在您可以按如下方式調用 function 並且僅當類型提示與每個 function 參數的類型匹配時才會起作用

In [42]: myFunc("hello", 1)
Out[42]: ('hello', 1)
In [43]: myFunc(1, 2)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-43-8bd42ff057a5> in <module>
----> 1 myFunc(1, 2)
# ... the rest of the traceback

暫無
暫無

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

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