Python has type hints in function arguments and function return types. Is there something similar for elements of a class? I would like to be able to use autocomplete in something like the following example:
class MyClass:
def hello(self):
print("Hello")
mylist = []
mylist.append(MyClass())
for i in mylist:
i.hello() # No autocomplete here
I understand this depends on the IDE but my question is about some language feature like the code hints mentioned above. Something like mylist = [] : MyClass
or similar
Yes it can. This works in WingIDE (and I'm sure in PyCharm as well):
from typing import List
class MyClass:
def hello(self):
print("Hello")
mylist: List[MyClass] = []
mylist.append(MyClass())
for i in mylist:
i.hello() # autocompleted here
If you use python before version 3.6, just use the old style syntax:
mylist = [] # type: List[MyClass]
The auto-completion works fine with either syntax.