Pycharm type hinting for list warning

Answered

Hello,

I just downloaded Pycharm Professional 2016.2.3, and for the simple example code below:

# -*- coding: utf-8 -*-

"""Simple test case"""


def test():
"""Simple test method"""
a = [1, 2, 3] # type: list[int]
print a[0].bit_length()
print a

Where I was trying to use local variable type hinting on the variable "a" to indicate that it is a list of integers.  Although the type hinting works, Pycharm gives me this warning on the type hinting line:

Class 'type' does not define '__getitem__', so the '[]' operator cannot be used on its instances.

This warning obviously makes no sense, and although it does the break the code, the yellow warning indicator on the right annoys me.  If this is not the right type hinting syntax for a list, what's the correct way?  Thanks.

4 comments
Comment actions Permalink

Hi there!

 

According to PEP-484 the proper syntax is actually "List[int]" (notice the capitalization). Also, don't forget to import the name from "typing" module first. As the rule of thumb, regardless of whether you use dedicated Python 3 syntax for annotations or type comments, a type hint must remain a valid executable Python expressions, and evaluating "list[int]" would indeed produce a TypeError at runtime.

0
Comment actions Permalink

What is the proper way around this in Python27?

Something like this?

from types import ListType

def foo():
a = [1,2,3] # type: ListType[int]
0
Comment actions Permalink

I've noticed the error which happens when using inline type hint doesn't occur when using the nextline type hint.

Example:

I'm not sure I understand why one would generate the error, while the other is ok.

 

It's also interesting that while the error (I should call it a warning) doesn't prevent the editor from using the type hint in autocomplete.

Example:

0
Comment actions Permalink

Hi Marcel,

 

As I noted, according to PEP 484 annotations used in type comments should remain valid Python expressions (we even inject Python fragments in such comments) and "list[int]" would fail at runtime if it was evaluated since "list" class indeed doesn't define "__getitem__" unlike "typing.List". It's perfectly ok, however, to use such annotation in a docstring because we use our own annotation syntax there introduced in python-skeletons quite a while back, and both formats happen to overlap in a few places. These subtle differences tend to confuse people, and I encourage you to stick to newer PEP 484 format: it's more versatile, better tailored for Python 3, supported by third-party tools like mypy, and we might drop support for python-skeletons altogether at some point in future.

As for why "# type: list[int]" works nonetheless, it's wrong, such malformed annotations should be ignored. I'll create a dedicated issue about that.

UPDATE: created the ticket

0

Please sign in to leave a comment.