I'm trying to use the Python function annotations (PEP 3107) as type hints for PyCharm, but failed to do so. The problem is probably related to my use of ABCMeta
:
import abc
class base(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def test(self):
pass
class deriv1(base):
def test(self):
return "deriv1"
class deriv2(base):
def test(self):
return "deriv2"
my_list = []
def append_to_list(el: base) -> list(base):
# def append_to_list(el):
# """
# :param el: item to add
# :type: base
# :return: items so far
# :rtype: list[base]
# """
my_list.append(el)
return my_list
append_to_list(deriv1())
a = append_to_list(deriv2())
for o in a:
print(o.test())
This code does not run. Instead, I get a TypeError: 'ABCMeta' object is not iterable
on the def append_to_list
line.
When I use the alternative function with docstring type hints (the commented lines in the code above), everything works great.
Is it possible to use annotations for this kind of type hinting?
It's not related to abc
but because you told Python to literally evaluate
list(base)
which is impossible because base
is not iterable. That's what the error message is telling you.
You need to change it to square brackets and wrap it in quotes (because the list
type is not subscriptable):
def append_to_list(el: base) -> 'list[base]':
or use typing.List
which is subscriptable:
from typing import List
def append_to_list(el: base) -> List[base]:
To indicate it's a list containing base
objects.