(original) (raw)
On 1 November 2017 at 23:48, Lukasz Langa <lukasz@langa.pl> wrote:
Runtime annotation resolution and class decorators
\--------------------------------------------------
Metaclasses and class decorators that need to resolve annotations for
the current class will fail for annotations that use the name of the
current class. Example::
def class\_decorator(cls):
annotations = get\_type\_hints(cls) # raises NameError on 'C'
print(f'Annotations for {cls}: {annotations}')
return cls
@class\_decorator
class C:
singleton: 'C' = None
This was already true before this PEP. The class decorator acts on
the class before it's assigned a name in the current definition scope.
Just a random idea: maybe this can be resolved by just updating the localns before calling get\_type\_hints() like this:
localns = locals().copy()
localns.update({cls.\_\_name\_\_: cls})
In general I like how the PEP is written now. I maybe would add examples for this
> the cases listed above might be
worked around by placing the usage
> in a if TYPE\_CHECKING: block.
> ...
> For named tuples, using the new
class definition syntax introduced in Python 3.6 solves the issue.
actually showing something like
if TYPE\_CHECKING:
Alias = List\[Tuple\[int, SomeClass\]\]
class NT(NamedTuple):
one: SomeClass
other: Alias
class SomeClass:
...
--
Ivan