简体   繁体   English

PyCharm - 尾随类型提示和行宽限制

[英]PyCharm - Trailing type hints and line width limit

In PyCharm, I typically use trailing type hints (not sure of the right way of calling them) for variables such as this: 在PyCharm中,我通常使用尾随类型提示 (不确定调用它们的正确方法)对于这样的变量:

my_var = my_other_variable  # type: MyObject

However, sometimes I already have a very long line which I cannot really split, or the type hint is a bit long, such as: 但是,有时我已经有一条很长的线,我无法真正拆分,或者类型提示有点长,例如:

my_var = my_really_long_variable_name  # type: QtWidgets.QVeryLongQtClassName

This would make the full line longer than my line width limit (79 characters), and hence PyCharm would flag a warning. 这将使整行比我的行宽限制(79个字符)更长,因此PyCharm会标记警告。

Hence, is there a way to put the type hint in a different line? 因此, 有没有办法将类型提示放在不同的行? I tried these but they do not seem to work: 我试过这些,但它们似乎不起作用:

# type: QtWidgets.QVeryLongQtClassName
my_var = my_really_long_variable_name

my_var = my_really_long_variable_name \
    # type: QtWidgets.QVeryLongQtClassName

The closest thing I can think of is this, which may not really shorten that much the line width: 我能想到的最接近的是这个,这可能并没有真正缩短线宽:

my_var = \
    my_really_long_variable_name  # type: QtWidgets.QVeryLongQtClassName

Otherwise, the only alternative I have is to do something like this: 否则,我唯一的选择是做这样的事情:

v = my_really_long_variable_name
my_var = v  # type: QtWidgets.QVeryLongQtClassName

The other alternative of shortening the type does not seem to work based on the tests I have done; 根据我所做的测试,缩短类型的另一种选择似乎不起作用; PyCharm seems to struggle recognising that my_var 's type is really QtWidgets.QVeryLongQtClassName in this case: 在这种情况下,PyCharm似乎很难认识到my_var的类型实际上是QtWidgets.QVeryLongQtClassName

t = QtWidgets.QVeryLongQtClassName
my_var = my_really_long_variable_name  # type: t

I found it very convenient to import the class names directly from the module for the type annotation usage. 我发现直接从模块导入类名以获取类型注释用法非常方便。 For example: 例如:

from QtWidgets import QVeryLongQtClassName
my_var = my_really_long_variable_name  # type: QVeryLongQtClassName

I have not encountered a problem like yours yet with this attitude. 我没有遇到像你这样的问题。

However, I found this version to be the most readable and convenient way to annotate a long line: 但是,我发现这个版本是注释长行最可读和最方便的方法:

my_var = \
    my_really_long_variable_name  # type: QtWidgets.QVeryLongQtClassName

UPDATE: Another way to implement this: 更新:实现此目的的另一种方法:

my_var = (
    my_really_long_variable_name
)  # type: QtWidgets.QVeryLongQtClassName

In addition, it is supported and does not cause problems in most IDEs. 此外,它受支持,并且不会在大多数IDE中引起问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM