You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -503,12 +502,12 @@ If you don't mind annotating *all* attributes, you can even drop the `field` and
503
502
>>> @define
504
503
... classAutoC:
505
504
... cls_var: typing.ClassVar[int] =5# this one is ignored
506
-
... l: typing.List[int] = Factory(list)
505
+
... l: list[int] = Factory(list)
507
506
... x: int=1
508
507
... foo: str="every attrib needs a type if auto_attribs=True"
509
508
... bar: typing.Any =None
510
509
>>> fields(AutoC).l.type
511
-
typing.List[int]
510
+
list[int]
512
511
>>> fields(AutoC).x.type
513
512
<class 'int'>
514
513
>>> fields(AutoC).foo.type
@@ -522,35 +521,39 @@ If you don't mind annotating *all* attributes, you can even drop the `field` and
522
521
523
522
The generated ``__init__`` method will have an attribute called ``__annotations__`` that contains this type information.
524
523
525
-
If your annotations contain strings (e.g. forward references),
524
+
If your annotations contain forward references,
526
525
you can resolve these after all references have been defined by using :func:`attr.resolve_types`.
527
526
This will replace the *type* attribute in the respective fields.
528
527
529
528
.. doctest::
530
529
531
-
>>> import typing
532
530
>>> from attr import fields, resolve_types
533
531
534
532
>>> @define
535
533
... classA:
536
-
... a: typing.List['A']
534
+
... a: 'list[A]'
537
535
... b: 'B'
538
536
...
539
537
>>> @define
540
538
... classB:
541
539
... a: A
542
540
...
543
541
>>> fields(A).a.type
544
-
typing.List[ForwardRef('A')]
542
+
'list[A]'
545
543
>>> fields(A).b.type
546
544
'B'
547
545
>>> resolve_types(A, globals(), locals())
548
546
<class 'A'>
549
547
>>> fields(A).a.type
550
-
typing.List[A]
548
+
list[A]
551
549
>>> fields(A).b.type
552
550
<class 'B'>
553
551
552
+
.. note::
553
+
554
+
If you find yourself using string type annotations to handle forward references, wrap the entire type annotation in quotes instead of only the type you need a forward reference to (so ``'list[A]'`` instead of ``list['A']``).
555
+
This is a limitation of the Python typing system.
556
+
554
557
.. warning::
555
558
556
559
``attrs`` itself doesn't have any features that work on top of type metadata *yet*.
0 commit comments