2017-06-19 24 views
2

如何註釋返回cls的實例的@classmethod?這是一個不好的例子:返回實例的類方法的MyPy註釋

class Foo(object): 
    def __init__(self, bar: str): 
     self.bar = bar 

    @classmethod 
    def with_stuff_appended(cls, bar: str) -> ???: 
     return cls(bar + "stuff") 

這會返回一個Foo但更準確地返回取的Foo子類是呼籲,與-> "Foo"這樣標註是不夠好。

+0

' - >'Foo''是正確的,這就是所有你可以(或應該)執行的返回值。 – jonrsharpe

回答

2

訣竅是註釋明確添加到cls參數,結合TypeVar,爲generics,並且Type,以represent a class rather then the instance itself,像這樣:

from typing import TypeVar, Type 

# Create a generic variable that can be 'Parent', or any subclass. 
T = TypeVar('T', bound='Parent') 

class Parent: 
    def __init__(self, bar: str) -> None: 
     self.bar = bar 

    @classmethod 
    def with_stuff_appended(cls: Type[T], bar: str) -> T: 
     # We annotate 'cls' with a typevar so that we can 
     # type our return type more precisely 
     return cls(bar + "stuff") 

class Child(Parent): 
    # If you're going to redefine __init__, make sure it 
    # has a signature that's compatible with the Parent's __init__, 
    # since mypy currently doesn't check for that. 

    def child_only(self) -> int: 
     return 3 

# Mypy correctly infers that p is of type 'Parent', 
# and c is of type 'Child'. 
p = Parent.with_stuff_appended("10") 
c = Child.with_stuff_appended("20") 

# We can verify this ourself by using the special 'reveal_type' 
# function. Be sure to delete these lines before running your 
# code -- this function is something only mypy understands 
# (it's meant to help with debugging your types). 
reveal_type(p) # Revealed type is 'test.Parent*' 
reveal_type(c) # Revealed type is 'test.Child*' 

# So, these all typecheck 
print(p.bar) 
print(c.bar) 
print(c.child_only()) 

通常情況下,你可以離開cls(和self )未加註釋,但如果您需要參考特定的子類,則可以添加一個explicit annotation。請注意,此功能仍處於試驗階段,在某些情況下可能會出現問題。您可能還需要使用從Github克隆的mypy的最新版本,而不是pypi上可用的 - 我不記得該版本是否支持classmethods的此功能。

+1

正常mypy工作:) – taway

+0

@taway - 呵呵,酷!我可以發誓它沒有,但我很高興聽到我錯了! – Michael0x2a

相關問題