简体   繁体   中英

Using mypy's generic self with python2 type comments

I have a case where I would like to use a generic self for typing with mypy. However I need to maintain python 2.7 compatibility, so I'm using the type comment syntax.

from typing import TypeVar

T = TypeVar('T', bound='Shape')

class Shape:
    def set_scale(self: T, scale: float) -> T:
        self.scale = scale
        return self

How do I translate this code to a type comment? Type comments omit the 'self' type, so the T definition gets lost:

    def set_scale(self, scale):
        # type: (float) -> T

You don't have to exclude self ; you simply have the option to do so:

When using the short form (eg # type: (str, int) -> None) every argument must be accounted for, except the first argument of instance and class methods ( those are usually omitted, but it's allowed to include them ).


From PEP-484, third note at the end of Suggested Syntax for Python 2.7 and straddling code

So you can write

def set_scale(self, scale):
    # type: (T, float) -> T

It's the job of the consumer of such a comment to count parameters and determine if self was omitted or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM