Skip to content

Commit 37af870

Browse files
committed
Recommend use of unquoted annotations in coding style guide
Revise coding-style advice to prefer unquoted annotations which are enabled by `from __future__ import annotations` Ref: https://peps.python.org/pep-0563/ Related to #1999
1 parent 11f0f51 commit 37af870

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

docs/dev/style.md

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -84,26 +84,32 @@ the sampler class is defined in `cirq.work.sampler.Sampler`). Code in `cirq-core
8484
typically cannot import and use `cirq.Sampler` directly because this could
8585
create an import cycle where modules import each other (perhaps indirectly).
8686
Instead, the import of the top-level `cirq` library can be guarded by the
87-
`TYPE_CHECKING` constant provided by `typing`, and the type annotation can be
88-
quoted so that it is not evaluated when the module is imported but rather during
89-
type-checking:
87+
`TYPE_CHECKING` constant provided by `typing`. In addition, the module needs to
88+
start with `from __future__ import annotations` so that annotations are skipped
89+
at the module import time and get only evaluated during type-checking when the
90+
`cirq` import is in effect.
9091

9192
```python
93+
from __future__ import annotations
94+
9295
from typing import TYPE_CHECKING
9396

9497
if TYPE_CHECKING:
9598
import cirq
9699

97-
def accepts_sampler(sampler: 'cirq.Sampler') -> None:
100+
def accepts_sampler(sampler: cirq.Sampler) -> None:
98101
...
99102
```
100103

101104
Use top-level `cirq.*` annotations like this when annotating new public types
102105
and classes. Older code may not adhere to this style and should be updated.
103106

104-
Note that type annotations may need to be quoted like this in other situations
105-
as well, such as when an annotation is a "forward reference" to a class defined
106-
later in the same file.
107+
Note that type annotations may need to be quoted when they act in expressions
108+
that are evaluated at the import time, for example,
109+
110+
```python
111+
MOMENT_OR_OPERATION = Union['cirq.Moment', 'cirq.Operation']
112+
```
107113

108114
## Nomenclature
109115

0 commit comments

Comments
 (0)