How do I get a type hint in this case? (Iterator)

How can I get this type of import to let me get a type hint for element (which has a type of 'Element')?


import xml.etree.cElementTree as ET
for event, elem in ET.iterparse(sys.argv[1]):
    print type(elem)
    #assert isinstance(elem, Element)
    if event == 'end':
        count += 1
    elem.clear() # discard the element


This does not work either:

import xml.etree.ElementTree
for event, elem in xml.etree.ElementTree.iterparse(sys.argv[1]):
    assert isinstance(elem, xml.etree.ElementTree.Element)
    if event == 'end':
        count += 1
    elem.clear() # discard the element


In neither case does Pycharm figure out the type of 'elem'.  What have I missed?
2 comments
Comment actions Permalink
Code completion for ElementTree is poor at the moment, it will be imporoved in PyCharm 3.0, follow PY-3850.

The cElementTree module is a binary file that has no Python source. PyCharm generates a skeleton file for its classes and functions but it cannot infer return types for it.

In the second example there is a known bug PY-9985 that results in etree resolving to xml.__all__ instead of xml.etree package. If you alias ElementTree as ET2, for exmaple, and put the assert isintance(elem, ET2.Element) instruction, then code completion works.

Note, that we are going to provide code completion for ElementTree classes even without assert instructions.
0
Comment actions Permalink
Thanks for the alias suggestion, but what's the exact syntax to make the alias?


Type hinting I think could be easier to diagnose in pycharm:
1) Rather than saying 'No documentation found.' list at least some hints about near matches or the search path tried.
2) Give us a way to create type hints on locals, other than isinstance().  I often KNOW the type, but have trouble getting pycharm to figure it out.
3) Give us a way to give type hints inside Django templates (See http://youtrack.jetbrains.com/issue/PY-7415 ).
0

Please sign in to leave a comment.