Why does ordering matter in Python type hinting?

◇◆丶佛笑我妖孽 提交于 2020-01-19 17:35:50

问题


Why is this ok

class Ship:

    def __init__(self, parent):
        self.parent = parent

class Fleet:

    def __init__(self):
        self.ships = []

    def add_ship(self, ship: Ship):
        self.ships.append(ship)

But this is not?

class Fleet:

    def __init__(self):
        self.ships = []

    def add_ship(self, ship: Ship):
        self.ships.append(ship)

class Ship:

    def __init__(self, parent):
        self.parent = parent

I know that you cannot have circular references in importing. However, this is not an import thing: both of these are in the same file. In both cases the definition of Ship is made, but it seems as though if Fleet is defined first it can't find the definition of Ship. This is not true if I used isinstance to check the type.

def add_ship(self, ship):
    if isinstance(ship, Ship): # works fine
        self.ships.append(ship)

However, that does not allow my IDE (PyCharm) to see the definition and autocomplete syntax.

In fact, the following design pattern seems to work fine

class Fleet:

    def __init__(self):
        self.ships = []

    def add_ship(self, ship):
        if isinstance(ship, Ship):
            self.ships.append(ship)

class Ship:

    def __init__(self, parent):
        if isinstance(parent, Fleet):
            self.parent = parent

But, again, does not allow for my IDE to figure out the types. This is Python 3.6.5/Anaconda/Windows 10.


回答1:


def add_ship(self, ship: Ship): is evaluated at definition time. At that time Ship is not defined yet.

if isinstance(ship, Ship): is evaluated only when add_ship is called. This will (hopefully) be only after Ship had been defined.

PEP 563 (implemented in Python 3.7 and above) solves this by making the type annotations evaluation lazy.

If you upgrade, you can add from __future__ import annotations to the top of the file and that example will work.

This will be fully implemented in Python 4.0, meaning from __future__ import annotations will not be needed.

Pre Python 3.7 solution

If you can't or don't want to upgrade to Python >= 3.7 you can use a string-literal annotation (which is also mentioned in the PEP I linked to):

def add_ship(self, ship: 'Ship'):


来源:https://stackoverflow.com/questions/54114140/why-does-ordering-matter-in-python-type-hinting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!