In the code below, I have a subclass Generic. If I try to create an instance after directly specifying the type (as in the case Bar), it seems like it is __init__never called. See below steps in PDB.
from typing import Generic, TypeVar
T = TypeVar('T')
class Foo(Generic[T]):
def __init__(self, value: T):
self.value = value
Bar = Foo[str]
foo = Foo('foo')
bar = Bar('bar')
print(type(foo), end=' ')
print(foo.value)
print(type(bar), end=' ')
print(bar.value)
According to the docs:
The base base class uses a metaclass that defines getitem (), so LoggedVar [t] is valid as a type:
Is this a mistake, or am I not understanding something?
EDIT
Going to the PDB for the case of Foo ('foo'), note __init__called at the end:
> /home/kjw53/test.py(1)<module>()
-> from typing import Generic, TypeVar
(Pdb) break /usr/lib/python3.5/typing.py:1078
Breakpoint 1 at /usr/lib/python3.5/typing.py:1078
(Pdb) c
> /usr/lib/python3.5/typing.py(1078)__new__()
-> return next_in_mro.__new__(_gorg(cls))
(Pdb) p cls
__main__.Foo[~T]
(Pdb) p next_in_mro
<class 'object'>
(Pdb) p _gorg(cls)
__main__.Foo[~T]
(Pdb) s
--Call--
> /usr/lib/python3.5/typing.py(858)_gorg()
-> def _gorg(a):
(Pdb) r
--Return--
> /usr/lib/python3.5/typing.py(863)_gorg()->__main__.Foo[~T]
-> return a
(Pdb) n
--Return--
> /usr/lib/python3.5/typing.py(1078)__new__()-><__main__.Foo...x7f57094b1a20>
-> return next_in_mro.__new__(_gorg(cls))
(Pdb) s
--Call--
> /home/kjw53/test.py(5)__init__()
-> def __init__(self, value: T):
Continuing, we now fall into the case Bar('bar'). A note is __init__not called even though everything else looks the same.
(Pdb) c
> /usr/lib/python3.5/typing.py(1078)__new__()
-> return next_in_mro.__new__(_gorg(cls))
(Pdb) p cls
__main__.Foo[str]
(Pdb) p next_in_mro
<class 'object'>
(Pdb) p _gorg(cls)
__main__.Foo[~T]
(Pdb) s
--Call--
> /usr/lib/python3.5/typing.py(858)_gorg()
-> def _gorg(a):
(Pdb) r
--Return--
> /usr/lib/python3.5/typing.py(863)_gorg()->__main__.Foo[~T]
-> return a
(Pdb) n
--Return--
> /usr/lib/python3.5/typing.py(1078)__new__()-><__main__.Foo...x7f57094b1a58>
-> return next_in_mro.__new__(_gorg(cls))
(Pdb) s
> /home/kjw53/test.py(13)<module>()
-> print(type(foo), end=' ')