PyCharm - trailing type hints and line width limit

In PyCharm, I usually use trailing type hints (not sure about the correct way to call them) for variables like:

my_var = my_other_variable  # type: MyObject

      

However, sometimes I already have a very long line that I cannot break, or the type hint is a bit long, like:

my_var = my_really_long_variable_name  # type: QtWidgets.QVeryLongQtClassName

      

This will cause the full length to be longer than my line width limit (79 characters) and hence PyCharm will flag a warning.

Hence, is there a way to put the type hint on another line? I've tried them but they don't 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 I can think of is something that might not cut the line width much:

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

      

Another alternative to type reduction doesn't work, based on the tests I've done; PyCharm doesn't seem to understand what the type is my_var

really QtWidgets.QVeryLongQtClassName

in this case:

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

      

+3


source to share


1 answer


I found it very convenient to import the class names directly from the module to use the annotation type. For example:

from QtWidgets import QVeryLongQtClassName
my_var = my_really_long_variable_name  # type: QVeryLongQtClassName

      

I haven't come across a problem like yours, but 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

      

Moreover, it is supported and does not cause problems in most IDEs.

+2


source







All Articles