In PyCharm, I typically use trailing type hints (not sure of the right way of calling them) for variables such as this:
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With