Debian Codegraph @

docs/guide/users/recommendations/python-code.md

raw symbols SCIP
1 # Python code best practices
2
3 This document describes some best practices to adopt when using Griffe, or when writing Python code that will be analyzed by Griffe.
4
5 ## Avoid member-submodule name shadowing
6
7 Sometimes we find that an `__init__` module defines or imports an object which has the same name as a submodule of the parent package.
8
9 **Case 1**
10
11 ```tree
12 package/
13 __init__.py
14 subpackage/
15 __init__.py
16 thing.py
17 ```
18
19 ```python title="package/subpackage/__init__.py"
20 thing = "thing from init module"
21 ```
22
23 ```python title="package/subpackage/thing.py"
24 other_thing = "other thing from thing submodule"
25 ```
26
27 We recommend not doing that.
28
29 Why? Because the `package.subpackage.thing` submodule can eventually **shadow** the `package.subpackage.thing` attribute. Try this:
30
31 ```bash
32 # Replicate the file tree from above.
33 mkdir -p package/subpackage
34 echo 'thing = "thing from init module"' > package/subpackage/__init__.py
35 echo 'other_thing = "other thing from thing submodule"' > package/subpackage/thing.py
36 # Run a Python interpreter.
37 python
38 ```
39
40 ```pycon
41 >>> from package import subpackage
42 >>> subpackage.thing
43 'thing from init module'
44 >>> # OK, but...
45 >>> from package.subpackage.thing import other_thing
46 >>> subpackage.thing
47 <module 'package.subpackage.thing' from 'package/subpackage/thing.py'>
48 ```
49
50 By simply importing from the `thing` submodule, the `thing` attribute of `subpackage` was overwritten by the `thing` submodule.
51
52 **Case 2**
53
54 In a particular case though, the situation improves: if we *import* `thing` in the init module instead of declaring it, then further imports will not overwrite anything:
55
56 ```python title="package/subpackage/__init__.py"
57 from package.subpackage.thing import thing
58 ```
59
60 ```python title="package/subpackage/thing.py"
61 thing = "thing from thing submodule"
62 ```
63
64 ```bash
65 # Update the modules.
66 echo 'from package.subpackage.thing import thing' > package/subpackage/__init__.py
67 echo 'thing = "thing from thing submodule"' > package/subpackage/thing.py
68 # Run a Python interpreter.
69 python
70 ```
71
72 ```pycon
73 >>> from package import subpackage
74 >>> subpackage.thing
75 'thing from thing'
76 >>> # OK
77 >>> from package.subpackage.thing import thing
78 >>> subpackage.thing
79 'thing from thing'
80 >>> # Still OK
81 ```
82
83 From an API perspective, and given that both cases are very similar but differ in behavior, we recommend not doing that either.
84
85 If the goal is to isolate a single object into its own module, to then expose it in the parent module, then it would make sense that this object is the only object of the submodule to be exposed in the public API, and therefore the submodule could be marked as private by prefixing its name with an underscore:
86
87 ```tree
88 package/
89 __init__.py
90 subpackage/
91 __init__.py
92 _thing.py
93 ```
94
95 With this, there is no ambiguity as to what `subpackage.thing` points to.
96
97 For the reasons mentioned above, **Griffe does not support this kind of name shadowing.** During static analysis, the submodule will take precedence over the attribute. During dynamic analysis, Griffe's behavior is undefined.
98
99 ## Avoid wildcard imports
100
101 Wildcard imports allow importing from a module all objects that do not start with an underscore `_`, or all objects that are listed in the module's `__all__` attribute, if it is defined.
102
103 ```tree
104 package/
105 __init__.py
106 module.py
107 ```
108
109 **Explicitly exposed to wildcard imports**
110
111 ```python title="package/module.py"
112 __all__ = [
113 "SomeClass",
114 "some_function",
115 "some_attribute",
116 ]
117
118 class SomeClass: ...
119 class SomeOtherClass: ...
120
121 def some_function(): ...
122 def some_other_function(): ...
123
124 some_attribute = 0
125 some_other_attribute = 1
126 ```
127
128 **Implicitly exposed to wildcard imports**
129
130 ```python title="package/module.py"
131 class SomeClass: ...
132 class _SomeOtherClass: ...
133
134 def some_function(): ...
135 def _some_other_function(): ...
136
137 some_attribute = 0
138 _some_other_attribute = 1
139 ```
140
141 In both cases, using a wildcard import will only import `SomeClass`, `some_function` and `some_attribute`, and not their "other" counterparts:
142
143 ```python title="package/__init__.py"
144 from package.module import *
145 ```
146
147 While we recommend declaring your public API with `__all__` lists, we do not recommend using wildcard imports.
148
149 In the implicit case, any other object imported in `module.py` will also be exported by the wildcard:
150
151 ```python title="package/module.py"
152 from somewhere_else import this, that
153
154 class SomeClass: ...
155 class _SomeOtherClass: ...
156
157 def some_function(): ...
158 def _some_other_function(): ...
159
160 some_attribute = 0
161 _some_other_attribute = 1
162 ```
163
164 Here, `this` and `that` will also be imported when we do `from package.module import *`. To prevent that, we would have to alias these names as such:
165
166 ```python title="package/module.py"
167 from somewhere_else import this as _this, that as _that
168 ```
169
170 ...which is not ideal.
171
172 It gets even worse if `module.py` itself uses wildcard imports:
173
174 ```python title="package/module.py"
175 from somewhere_else import *
176 ```
177
178 Now using `from package.module import *` will import all objects that do not start with an underscore declared in the module, but also all the objects imported by it that do not start with an underscore, and also all the objects imported by the modules of the imported objects that do not start with an underscore, etc., recursively. Soon enough, we end up with dozens and dozens of objects exposed in `package`, while just a few of them are useful/meaningful to users.
179
180 Not only that, but it also increases the risk of creating cycles in imports. Python can handle some of these cycles, but static analysis tools such as Griffe can have a much harder time trying to resolve them.
181
182 In the explicit case, the situation improves, as only the objects listed in `__all__` will be exported to the modules that wildcard imports them. It effectively stops namespace pollution, but it does not remove the risk of cyclic imports, only decreases it.
183
184 We have seen code bases where parent modules wildcard imports from submodules, while these submodules also wildcard imports from the parent modules... Python somehow handles this, but it is *hell* to handle statically, and it is just too error prone (cyclic imports, name shadowing, namespaces become dependent on the order of imports, etc.).
185
186 For these reasons, we recommend not using wildcard imports. Instead, we recommend declaring your public API explicitly with `__all__`, and combining `__all__` lists together if needed:
187
188 ```tree
189 package/
190 __init__.py
191 module.py
192 other_module.py
193 ```
194
195 Completely explicit:
196
197 ```python title="package/__init__.py"
198 from package.module import only, needed, objects
199 from package.other_module import some, more
200
201 __all__ = [
202 "only",
203 "needed",
204 "some",
205 "function",
206 ]
207
208 def function(): ...
209 ```
210
211 Combining `__all__` lists:
212
213 ```python title="package/__init__.py"
214 from package.module import only, needed, objects, __all__ as module_all
215 from package.other_module import some, more, __all__ as other_module_all
216
217 __all__ = [
218 *module_all,
219 *other_module_all,
220 "function",
221 ]
222
223 def function(): ...
224 ```
225
226 Most Python linting tools allow you to forbid the use of wildcard imports.
227
228 ## Prefer canonical imports
229
230 Within your own code base, we recommend using canonical imports. By canonical, we mean importing objects from the module they are declared in, and not from another module that also imports them.
231
232 Given the following tree:
233
234 ```tree
235 package/
236 __init__.py
237 module_a.py
238 module_b.py
239 ```
240
241 ```python title="package/module_a.py"
242 from package.module_b import thing
243 ```
244
245 ```python title="package/module_b.py"
246 thing = True
247 ```
248
249 Don't do that:
250
251 ```python title="package/__init__.py"
252 from package.module_a import thing # Indirect import, bad.
253 ```
254
255 Instead, do this:
256
257 ```python title="package/__init__.py"
258 from package.module_b import thing # Canonical import, good.
259 ```
260
261 ---
262
263 We especially recommend canonical imports over indirect imports from sibling modules passing through the parent:
264
265 ```python title="package/__init__.py"
266 from package.module_a import thing # Canonical import, good.
267 ```
268
269 ```python title="package/module_a.py"
270 thing = True
271 ```
272
273 ```python title="package/module_b.py"
274 from package import thing # Indirect import passing through parent, bad.
275
276 # Do this instead:
277 from package.module_a import thing # Canonical import, good.
278 ```
279
280 ---
281
282 Similarly, avoid exposing the API of external packages from your own package and recommending to use this indirect API.
283
284 ```python title="package.py"
285 import numpy as np
286
287 __all__ = ["np"] # Bad.
288
289 # Recommending users to do `from package import np`
290 # or `import package; package.np.etc`: bad.
291 ```
292
293 Instead, let users import Numpy themselves, with `import numpy as np`. This will help other analysis tools, for example to detect that Numpy is used directly and should therefore be listed as a dependency. To quote [PEP 8](https://peps.python.org/pep-0008/#public-and-internal-interfaces):
294
295 > Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module’s API, such as os.path or a package’s `__init__` module that exposes functionality from submodules.
296
297 Emphasis on *exposes functionality from submodules*: PEP 8 does not state *exposing functionality from external packages*.
298
299 ---
300
301 Using canonical imports provides several benefits:
302
303 - it can reduce the risk of cyclic imports
304 - it can increase performance by reducing hoops and importing less things (for example by not passing through a parent module that imports many things from siblings modules)
305 - it makes the code more readable and easier to refactor (less indirections)
306 - it makes the life of static analysis tools easier (less indirections)
307
308 We recommend using the [canonical-imports](https://github.com/15r10nk/canonical-imports) tool to automatically rewrite your imports as canonical.
309
310 Note however that we recommend using public imports (importing from the "public" locations rather than the canonical ones) when:
311
312 - importing from other packages
313 - importing from your own package within your tests suite
314
315 Apply these recommendations at your discretion: there may be other special cases where it might not make sense to use canonical imports.
316
317 ## Make your compiled objects tell their true location
318
319 Python modules can be written in other languages (C, C++, Rust) and compiled. To extract information from such compiled modules, we have to use dynamic analysis, since sources are not available.
320
321 A practice that seems common in projects including compiled modules in their distributions is to make the compiled modules private (prefix their names with an underscore), and to expose their objects from a public module higher-up in the module layout, for example by wildcard importing everything from it.
322
323 ```tree
324 package/
325 __init__.py
326 module.py
327 _module.cpython-312-x86_64-linux-gnu.so
328 ```
329
330 ```python title="package/module.py"
331 from package._module import *
332 ```
333
334 Since the objects are exposed in `package.module` instead of `package._module`, developers sometimes decide to make their compiled objects lie about their location, and make them say that they are defined in `package.module` instead of `package._module`. Example:
335
336 ```pycon
337 >>> from package._module import MyObject
338 >>> MyObject.__module__
339 'package.module'
340 ```
341
342 **Don't do that.**
343
344 When using dynamic analysis and inspecting modules, Griffe must distinguish objects that were declared in the inspected module from objects that were imported from other modules. The reason is that if we didn't care where objects come from, we could end up inspecting the same objects and their members again and again, since they can be imported in many places. This could lead to infinite loops, recursivity errors, and would generally decrease performance.
345
346 So, when Griffe inspects a member of the compiled `_module`, and this member lies and says it comes from `package.module`, Griffe thinks it was imported. It means that Griffe will record the object as an indirection, or alias, instead of visiting it in-place. But that is wrong: the object was actually declared in the module, and should not have been recorded as an indirection.
347
348 Fortunately, we were able to put some guard-rails in place, which means that the case above where the compiled and public modules have the same name, except for the leading underscore, is supported, and will not trigger errors. But other cases where modules have different names will trigger issues, and we have to special case them in Griffe itself, after issues are reported.
349
350 Please, use your framework features to correctly set the `__module__` attribute of your objects (functions, classes and their methods too) as their *canonical location*, not their public location or any other location in the final package.
351
352 For example with [PyO3](https://github.com/PyO3/pyo3):
353
354 ```rust
355 // Your module is compiled and added as `_module` into `package`,
356 // but its objects are exposed in `package` or `package.module`.
357 // Set `module = "package._module"`, not `module = "package"` or `module = "package.module"`!
358 #[pyclass(name = "MyClass", module = "package._module")]
359 struct MyClass {
360 // ...
361 }
362 ```
363
364 Some modules of the standard library are guilty of this too, and do so inconsistently (`ast` and `_ast`, `io` and `_io`, depending on the Python version...). For this reason, when checking if an object was declared in the currently inspected module, Griffe ultimately considers that any qualified name is equal to itself with each component stripped from leading underscores:
365
366 ```python
367 a.b.c == _a.b.c
368 a.b.c == _a._b._c
369 a.__b._c == __a.b.c
370 ...
371 ```
372
373 When the qualified name of the object's parent module and the currently inspected module match like above, the object is inspected in-place (added as a member of the currently inspected module) instead of created as an alias.
374
375 ## Avoid forward references in base classes
376
377 Python's type system will let you use forward references in generic types when they are used as base classes. For example:
378
379 === "Before Python 3.12"
380
381 ```python
382 from typing import TypeVar, Generic
383
384 T = TypeVar('T')
385
386
387 class Foo(Generic[T]):
388 ...
389
390
391 class FooBar(Foo['Bar']):
392 ...
393
394
395 class Bar:
396 ...
397 ```
398
399 === "Python 3.12+"
400
401 ```python
402 class Foo[T]:
403 ...
404
405
406 class FooBar(Foo['Bar']):
407 ...
408
409
410 class Bar:
411 ...
412 ```
413
414 While Griffe will load this code without error, the `'Bar'` forward reference won't be resolved to the actual `Bar` class. As a consequence, downstream tools like documentation renderers won't be able to output a link to the `Bar` class. We therefore recommend to avoid using forward references in base classes, if possible.
415
416 Instead, you can try one of the following approach:
417
418 - declare or import the `Bar` class earlier
419 - declare a proper type:
420
421 ```python
422 class Foo[T]:
423 ...
424
425
426 type TBar = Bar
427
428
429 class FooBar(Foo[TBar]):
430 ...
431
432
433 class Bar:
434 ...
435 ```
436
437 - make `FooBar` generic again but with a default type:
438
439 ```python
440 class Foo[T]:
441 ...
442
443
444 class FooBar[T=Bar](Foo[T]):
445 ...
446
447
448 class Bar:
449 ...
450 ```