如何键入提示具有不同类型值的字典

问题描述 投票:6回答:2

当将字典声明为文字时,有没有一种方法可以提示我特定键的值?

然后,进行讨论:是否有关于Python中字典键入的指导原则?我想知道在字典中混合类型是否被认为是不好的做法。

这里是一个例子:

考虑在类的__init__中声明字典:

(免责声明:我在示例中意识到,某些.elements条目可能更适合作为类属性,但这只是为了示例)。

class Rectangle:
    def __init__(self, corners: Tuple[Tuple[float, float]], **kwargs):
        self.x, self.z = corners[0][0], corners[0][1]
        self.elements = {
            'front': Line(corners[0], corners[1]),
            'left': Line(corners[0], corners[2]),
            'right': Line(corners[1], corners[3]),
            'rear': Line(corners[3], corners[2]),
            'cog': calc_cog(corners),
            'area': calc_area(corners),
            'pins': None
        }


class Line:
    def __init__(self, p1: Tuple[float, float], p2: Tuple[float, float]):
        self.p1, self.p2 = p1, p2
        self.vertical = p1[0] == p2[0]
        self.horizontal = p1[1] == p2[1]

当我键入以下内容时

rec1 = Rectangle(rec1_corners, show=True, name='Nr1')
rec1.sides['f...

Pycharm会为我建议'front'。更好的是,当我这样做时

rec1.sides['front'].ver...

Pycharm会建议.vertical

因此Pycharm会记住该类__init__中字典文字声明中的键,以及它们的值的预期类型。或更确切地说:它期望任何值都具有文字声明中的任何一种类型-可能与我执行self.elements = {} # type: Union[type1, type2]会执行的操作相同。无论哪种方式,我都觉得它很有帮助。

如果您的函数的输出类型带有提示,Pycharm也将考虑到这一点。

因此,假设在上面的Rectangle示例中,我想指出pinsPin对象的列表...如果pins是普通的类属性,则应该是

    self.pins = None  # type: List[Pin]

((已完成必要的进口)

是否可以在字典文字声明中提供相同类型的提示?

以下内容不是实现了我想要的功能:

在文字声明的末尾添加Union[...]类型提示吗?

            'area': calc_area(corners),
            'pins': None
        }  # type: Union[Line, Tuple[float, float], float, List[Pin]]

向每行添加类型提示:

            'area': calc_area(corners),  # type: float
            'pins': None  # type: List[Pin]
        }

这种事情是否有最佳实践?

更多背景:

我在PyCharm中使用Python,并且广泛使用了打字,因为它可以帮助我在进行过程中预测和验证我的工作。当我创建新类时,有时还会将一些不常用的属性放入字典中,以避免过多的属性使对象混乱(这在调试模式下很有用)。

python dictionary pycharm type-hinting typing
2个回答
6
投票

您正在寻找TypedDict。目前,它仅是一个仅适用于mypy的扩展,但不久的将来还有计划将make it an officially sanctioned type。不过,我不确定PyCharm是否支持此功能。

所以,就您而言,您会这样做:

from mypy_extensions import TypedDict

RectangleElements = TypedDict('RectangleElements', {
    'front': Line,
    'left': Line,
    'right': Line,
    'rear': Line,
    'cog': float,
    'area': float,
    'pins': Optional[List[Pin]]
})

class Rectangle:
    def __init__(self, corners: Tuple[Tuple[float, float]], **kwargs):
        self.x, self.z = corners[0][0], corners[0][1]
        self.elements = {
            'front': Line(corners[0], corners[1]),
            'left': Line(corners[0], corners[2]),
            'right': Line(corners[1], corners[3]),
            'rear': Line(corners[3], corners[2]),
            'cog': calc_cog(corners),
            'area': calc_area(corners),
            'pins': None
        }  # type: RectangleElements

如果您使用的是Python 3.6+,则可以使用class-based syntax进行更为优美的输入。

不过,在您的特定情况下,我认为大多数人只会将这些数据存储为常规字段,而不是字典。我敢肯定,尽管您已经考虑了该方法的优缺点,所以我将不为您讲解。


0
投票

经过更多的研究,到目前为止,我能找到的最佳解决方法是确保类Pin可以返回某种占位符,然后将占位符用作文字声明中的值。

因此:

class Pin:
    def __init__(self, **kwargs):
        if len(kwargs) == 0:
            return

现在,在OP中的示例中,我可以执行以下操作来实现我想要的目标:

        ...
        'area': calc_area(corners),
        'pins': List[Pin(),]
    } 

但是,如果我有一个或多个基本类型作为条目,则将无法使用。

        ...
        'area': calc_area(corners),
        'pins': List[Pin(),]
        'color': None
        'lap_times': None
    } 

其中color需要一个字符串,并且lap_times期望包含浮点数的列表...

在这种情况下,最佳解决方法是

        ...
        'area': calc_area(corners),
        'pins': List[Pin(),]
        'color': 'blue'
        'lap_times': [0.,]
    }

    self.elements['color'], self.elements['lap_times'] = None, None

这两个看上去都不是很优雅,所以我仍然希望有人可以提出更好的建议。

© www.soinside.com 2019 - 2024. All rights reserved.