Support annotations for homogeneous tuples (PY-18762)

Answered

https://youtrack.jetbrains.com/issue/PY-18762

 

This ticket was closed back for version 2016.1, but I'm still having trouble getting type inference to work for homogeneous tuples:

 

 

    def x(my_tuple):

        """

            @type my_tuple: Tuple[int, ...]

        """

        for x in my_tuple:

            x # <- type should be int, but instead is Any

 

I've also tried:

 

   @type my_tuple: (int, )

   @type my_tuple: (int, ...)

   @type my_tuple: Tuple[int]

 

and none seem to work. Has this feature not been shipped yet?

4 comments
Comment actions Permalink

Could you put the comment on that ticket? You're more likely to get a good back-and-forth with Mikhail that way, and the ticket can be re-opened if there's a flaw.

0
Comment actions Permalink

Hi Tom,

It has been shipped, but such notation is recognized only in places "approved" by PEP 484, i.e. either in PEP 3107 function annotations or in type comments:

 

from typing import Tuple


def f(xs: Tuple[int, ...]):
for x in xs:
print(x.bit_length())


def g1(xs):
# type: (Tuple[int, ...]) -> None
for x in xs:
print(x.bit_length())


def g2(
xs # type: Tuple[int, ...]
):
# type: (...) -> None
for x in xs:
print(x.bit_length())

 

0
Comment actions Permalink

Thank you Mikhail!

Is docstring support a feature that would be considered for future versions of PyCharm? It sounds like they may be falling out of favor in general considering Guido's comment here: https://github.com/python/typing/issues/146 .

We considered that (and the advantages you mention aren't new to me) but we strongly prefer the approach currently advocated in the PEP. There are already several ways to get around the downsides, e.g. using stub files or stringified annotations. Adding more options will not help.

0
Comment actions Permalink

For me the main point of PEP 484 is introduction of the universal way to annotate Python code, so that not only PyCharm but other tools like mypy and pytype could benifit from type hints. Unfortunately, docstrings are not very suitable for storing structured information about types and it's not that easy to reliably extract this information from them (especially taking into account that there are many docsting formats around). If we encouraged the use of type hints in docstrings, where other tools cannot find them, it would undermine the whole purpose of the unified standard. Though, I totally agree that it's weird that one has to use different syntax for type annotations in different places. Probably, we'll support whole PEP 484 annotation syntax in docstrings at some point just for the sake of completeness (together with some warning about it), but it's not our priority right now.

0

Please sign in to leave a comment.