打字:如果类属性是类型的别名,如何获得?

发布于 2025-01-30 09:57:47 字数 382 浏览 1 评论 0原文

例如:

import typing

tuple2 = typing.Tuple[float,float]

class A:
  a: tuple2 = (1.,1.)

print(typing.get_type_hints(A)['a'])

这是预期的:typing.tuple [float,float]

是否存在类似的东西?

print(some_other_function(A)['a'])
# prints: "tuple2" 

For example:

import typing

tuple2 = typing.Tuple[float,float]

class A:
  a: tuple2 = (1.,1.)

print(typing.get_type_hints(A)['a'])

This prints, as expected: typing.Tuple[float, float]

Does something simular to this exists?

print(some_other_function(A)['a'])
# prints: "tuple2" 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

后来的我们 2025-02-06 09:57:47

tuple2只是一个变量,它是指typing.tuple [float,float]。通常,除非您在检查变量名称空间中做奇怪的事情,否则您无法根据变量的值获得名称。

您可能要做的就是使用typing.newtype来定义一种实际的新类型:

>>> Tuple2 = typing.NewType("Tuple2", typing.Tuple[float, float])
>>> class A:
...     a: Tuple2 = Tuple2((1, 1))
...
>>> typing.get_type_hints(A)['a'].__name__
'Tuple2'

请注意,newType与别名不同;类型的Checkers将其视为您从中得出的类型的子类型,因此,如果将某些内容声明为tuple2,则需要将其定义为tuple2((1,1,1))而不是常规1,1元组。实际上,newType的行为总是与父类型完全相同,因此,如果您不使用类型的检查器,则差异并不重要。

如果您真的想获得别名的名称,则可以查看globals(),例如:

>>> tuple2 = typing.Tuple[float,float]
>>> [k for k, v in globals().items() if v == typing.Tuple[float, float]]
['tuple2']

但这不是很好,因为很可能有多个名称相同的值,如果有的话,运行时无法弄清楚哪种类型的别名。

tuple2 is just a variable that refers to typing.Tuple[float,float]. In general, you can't get the name of a variable based on its value, unless you do weird stuff with inspecting the variable namespace.

What you might want to do is use typing.NewType to define an actual new type:

>>> Tuple2 = typing.NewType("Tuple2", typing.Tuple[float, float])
>>> class A:
...     a: Tuple2 = Tuple2((1, 1))
...
>>> typing.get_type_hints(A)['a'].__name__
'Tuple2'

Note that a NewType is not the same as an alias; type checkers will consider it to be a subtype of the type that you derive it from, so if you declare something as a Tuple2 you need to define it as Tuple2((1, 1)) rather than a regular 1, 1 tuple. In practice, the newtype always behaves exactly the same as the parent type, so if you aren't using a type checker the difference is unimportant.

If you really want to get the name of an alias, you could look at globals(), e.g.:

>>> tuple2 = typing.Tuple[float,float]
>>> [k for k, v in globals().items() if v == typing.Tuple[float, float]]
['tuple2']

but this is not great because there might well be multiple names for the same value, and if there are, there's no way at runtime to figure out which alias was used for a particular type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文