打字:如果类属性是类型的别名,如何获得?
例如:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
tuple2
只是一个变量,它是指typing.tuple [float,float]
。通常,除非您在检查变量名称空间中做奇怪的事情,否则您无法根据变量的值获得名称。您可能要做的就是使用
typing.newtype
来定义一种实际的新类型:请注意,
newType
与别名不同;类型的Checkers将其视为您从中得出的类型的子类型,因此,如果将某些内容声明为tuple2
,则需要将其定义为tuple2((1,1,1))
而不是常规1,1
元组。实际上,newType的行为总是与父类型完全相同,因此,如果您不使用类型的检查器,则差异并不重要。如果您真的想获得别名的名称,则可以查看
globals()
,例如:但这不是很好,因为很可能有多个名称相同的值,如果有的话,运行时无法弄清楚哪种类型的别名。
tuple2
is just a variable that refers totyping.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: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 aTuple2
you need to define it asTuple2((1, 1))
rather than a regular1, 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.: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.