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
Copy file name to clipboardexpand all lines: docs/typed-libraries.md
+31-13
Original file line number
Diff line number
Diff line change
@@ -13,13 +13,11 @@ These recommendations are intended to provide the following benefits:
13
13
## Inlined Type Annotations and Type Stubs
14
14
[PEP 561](https://www.python.org/dev/peps/pep-0561/) documents several ways type information can be delivered for a library: inlined type annotations, type stub files included in the package, a separate companion type stub package, and type stubs in the typeshed repository. Some of these options fall short on delivering the benefits above. We therefore provide the following more specific guidance to library authors.
15
15
16
-
*All libraries should include inlined type annotations for the functions, classes, methods, and constants that comprise the public interface for the library.*
16
+
All libraries should include inlined type annotations for the functions, classes, methods, and constants that comprise the public interface for the library.
17
17
18
18
Inlined type annotations should be included directly within the source code that ships with the package. Of the options listed in PEP 561, inlined type annotations offer the most benefits. They typically require the least effort to add and maintain, they are always consistent with the implementation, and docstrings and default parameter values are readily available, allowing language servers to enhance the development experience.
19
19
20
-
There are cases where inlined type annotations are not possible — most notably when a library’s exposed functionality is implemented in a language other than Python.
21
-
22
-
*Libraries that expose symbols implemented in languages other than Python should include stub (“.pyi”) files that describe the types for those symbols. These stubs should also contain docstrings and default parameter values.*
20
+
There are cases where inlined type annotations are not possible — most notably when a library’s exposed functionality is implemented in a language other than Python. Libraries that expose symbols implemented in languages other than Python should include stub (“.pyi”) files that describe the types for those symbols. These stubs should also contain docstrings and default parameter values.
23
21
24
22
In many existing type stubs (such as those found in typeshed), default parameter values are replaced with with “...” and all docstrings are removed. We recommend that default values and docstrings remain within the type stub file so language servers can display this information to developers.
25
23
@@ -74,22 +72,33 @@ Variables:
74
72
75
73
Type annotations can be omitted in a few specific cases where the type is obvious from the context:
76
74
77
-
* A class or instance variable does not require an annotation if the class inherits from another class that has provided an annotation for the variable of the same name. The type is inherited from the parent class in this case.
78
75
* Constants that are assigned simple literal values (e.g. `RED = '#F00'` or `MAX_TIMEOUT = 50` or `room_temperature: Final = 20`). A constant is a symbol that is assigned only once and is either annotated with `Final` or is named in all-caps. A constant that is not assigned a simple literal value requires explicit annotations, preferably with a `Final` annotation (e.g. `WOODWINDS: Final[List[str]] = ['Oboe', 'Bassoon']`).
79
76
* Enum values within an Enum class do not require annotations because they take on the type of the Enum class.
80
77
* Type aliases do not require annotations. A type alias is a symbol that is defined at a module level with a single assignment where the assigned value is an instantiable type, as opposed to a class instance (e.g. `Foo = Callable[[Literal["a", "b"]], Union[int, str]]` or `Bar = Optional[MyGenericClass[int]]`).
81
78
* The “self” parameter in an instance method and the “cls” parameter in a class method do not require an explicit annotation.
82
79
* The return type for an `__init__` method does not need to be specified, since it is always `None`.
83
80
* The following module-level symbols do not require type annotations: `__all__`,`__author__`, `__copyright__`, `__email__`, `__license__`, `__title__`, `__uri__`, `__version__`.
84
81
* The following class-level symbols do not require type annotations: `__class__`, `__dict__`, `__doc__`, `__module__`, `__slots__`.
82
+
* A variable is assigned in only one location using a simple assignment expression and the right-hand side of the assignment is a literal value (e.g. `1`, `3.14`, `"hi"`, or `MyEnum.Value`) or an identifier that has a known type that doesn't depend on type narrowing logic.
83
+
84
+
85
+
### Ambiguous Types
86
+
87
+
When a symbol is missing a type annotation, a type checker may be able to infer its type based on contextual information. However, type inference rules are not standardized and differ between type checkers. A symbol is said to have an “ambiguous type” if its type may be inferred differently between different Python type checkers. This can lead to a bad experience for consumers of the library.
88
+
89
+
Ambiguous types can be avoided by providing explicit type annotations.
90
+
85
91
86
-
### Examples of known and unknown types
92
+
### Examples of known, ambiguous and unknown types
87
93
```python
88
94
89
-
# Variable with unknown type
95
+
# Variable with known type (unambiguous because it uses a literal assignment)
96
+
a =3
97
+
98
+
# Variable with ambiguous type
90
99
a = [3, 4, 5]
91
100
92
-
# Variable with known type
101
+
# Variable with known (declared) type
93
102
a: List[int] = [3, 4, 5]
94
103
95
104
# Type alias with partially unknown type (because type
@@ -148,7 +157,7 @@ class MyClass:
148
157
# Class with partially unknown type
149
158
classMyClass:
150
159
# Missing type annotation for class variable
151
-
height =2.0
160
+
height =None
152
161
153
162
# Missing input parameter annotations
154
163
def__init__(self, name, age):
@@ -161,22 +170,31 @@ class MyClass:
161
170
...
162
171
163
172
# Class with partially unknown type
164
-
classBaseClass:
173
+
classBaseClass1:
165
174
# Missing type annotation
166
-
height =2.0
175
+
height:=2.0
167
176
168
177
# Missing type annotation
169
178
defget_stuff(self):
170
179
...
171
180
172
181
# Class with known type (because it overrides all symbols
173
182
# exposed by BaseClass that have incomplete types)
174
-
classDerivedClass(BaseClass):
183
+
classDerivedClass1(BaseClass1):
175
184
height: float
176
185
177
186
defget_stuff(self) -> str:
178
187
...
179
188
189
+
# Class with known type
190
+
classBaseClass2:
191
+
height: float=2.0
192
+
193
+
# Class with ambiguous type
194
+
classDerivedClass2(BaseClass2):
195
+
# Missing type annotation, could be inferred as float or int
196
+
height =1
197
+
180
198
# Class with partially unknown type because base class
181
199
# (dict) is generic, and type arguments are not specified.
182
200
classDictSubclass(dict):
@@ -189,7 +207,7 @@ Pyright provides a feature that allows library authors to verify type completene
189
207
190
208
`pyright --verifytypes <lib>`
191
209
192
-
Pyright will analyze the library, identify all symbols that comprise the interface to the library and emit errors for any symbols whose types are unknown. It also produces a “type completeness score” which is the percentage of symbols with known types.
210
+
Pyright will analyze the library, identify all symbols that comprise the interface to the library and emit errors for any symbols whose types are ambiguous or unknown. It also produces a “type completeness score” which is the percentage of symbols with known types.
193
211
194
212
To see additional details (including a full list of symbols in the library), append the `--verbose` option.
0 commit comments