python类型注解_Python的:把当前类的返回类型注释

1586010002-jmsa.png

In python 3 I can make arguments and return type annotations. Example:

class Graph:

def __init__(self, V: int, E: int, edges: list):

pass

@classmethod

def fromfile(cls, readobj: type(sys.stdin)):

pass

def V(self) -> int:

pass

def E(self) -> int:

pass

The problem is I can't make an annotation with return type of the current class (Graph), which is not defined yet.

Example:

class Graph:

def reverse(self) -> Graph:

pass

This code goes with error

def reverse(self) -> Graph:

NameError: name 'Graph' is not defined

These annotations are really useful both for documenting and allowing IDE to recognize argument and return types => enable autocomplete

UPD:

So what I came up is this is either impossible or requires some hacks I don't like, so I decided to use just def reverse (self) -> 'Graph':

which is understandable for documentation although breaks the rule. The downside is that it doesn't work for IDE autocomplete.

解决方案

So now after a while I can say that decision I took was using -> 'Graph' instead of -> Graph. It does not make my IDE (PyCharm) able to recognize a type this way but it just works well enough for documentation purposes.

Another possible solution I could use was changing annotation at runtime but that doesn't solve the problem with documentation - you won't want to look for type declarations somewhere in the middle of sources...

The problem has roots in recognizing class object before the class was actually defined. That is simply impossible to do in python.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值