PEP 484
In Python & ge; 3.0, you can use function annotations ( PEP 3107 ) with semantics like hinting PEP 0484 . Although the last sentence was accepted only in Python 3.5 and will be conditional until version 3.6 , it is syntactically inverse compatible with all versions of Python that support PEP 3107, so using hint annotations in any version 3.x of Python should at least not hurt . [1]
Does your IDE or Interactive Interpreter (REPL) help improve autocomplete to this IDE or interpreter and, possibly, its settings even for Python & ge; 3.5.
For Python 2, an alternative notation using comments is available that tools supporting PEP 0484 may or may not be respected.
Add the type tips you care about
See how annotations (Python 3.x) will look for your code. (Comment based, Pinton-2.x-compatible hint remains as an exercise for the reader.)
To indicate that iterating over MyList instances gives MyClass objects, we return the return type __iter__() by adding -> (an arrow made of minus sign and a larger sign) after defining the colon function, followed by the return type. __iter__() itself does not return MyClass , it returns an iterator. To indicate that it should be an iterator over MyClass , we use the generic Iterator abstract base class from typing module [2] :
from typing import Iterator class MyClass: # ... class MyList: # ... def __iter__(self): -> Iterator[MyClass] return iter(self.list)
To keep this promise, self.list should only contain instances of MyClass . Therefore, let me kindly ask our callers to provide such, by type-hinting argument __init__() :
from typing import Iterator, Iterable # ... class MyList: def __init__(self, list: Iterable[MyClass]): self.list = list def __iter__(self): -> Iterator[MyClass] return iter(self.list)
Note that I chose the generic abstract base class Iterable , and not the more specific List generic abstract base class (and Mapping , Sequence or AbstractSet ), since your implementation depends only on iter(...) .
[1] with the possible exception of readability in abuse. So, as Mark writes , “please use a type-type response” if you use them.
[2] is included in Python & ge; 3.5. For lower versions, use the backport installed with pip install typing .