Skip to content

Commit 347162f

Browse files
committed
copy: Provide top-level documentation.
This commit adds documentation for the `copy` module, explaining why the module may require some changes in the objects being copied to behave as CPython. Unlike CPython, MicroPython does not provide default implementations for either `__reduce__` or `__reduce_ex__`, which are used by the copy module as the fallback methods to create copies of non-trivial objects. These methods aren't provided by default to minimise both the footprint of the interpreter binary and the RAM taken by object instances. Users who want simpler ways to allow object copies can implement `__copy__` and `__deepcopy__` instead, as mentioned in CPython's documentation for the `copy` module. Arguably the lack of `__reduce__` and `__reduce_ex__` could also be mentioned in MicroPython's own documentation as part of the differences from CPython, but it doesn't hurt to mention more module-specific caveats in here too. This should, in theory, keep user expectations in check w.r.t. the behaviour of this specific module. Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
1 parent 00efb6c commit 347162f

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

python-stdlib/copy/README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# copy
2+
3+
Non-trivial objects (eg. classes) instantiated by CPython are usually able to
4+
be copied by methods of this module without any modification, as the copying
5+
mechanism makes use of two functions (`__reduce__` and `__reduce_ex__`) that
6+
are added to instances by CPython itself.
7+
8+
MicroPython does not do that, to keep the interpreter's binary size down and to
9+
and to limit the RAM footprint of object instances. This means that this
10+
module is not able to copy non-trivial objects without specific changes to your
11+
code.
12+
13+
The `copy` module methods look for two methods being available in an instance:
14+
[`__copy__`](https://docs.python.org/3/library/copy.html#object.__copy__) and
15+
[`__deepcopy__`](https://docs.python.org/3/library/copy.html#object.__deepcopy__),
16+
and the module will call those functions to create a copy (either shallow or
17+
deep) of the object. Implementing either of those methods in a class will
18+
allow instances of that class to be copied both in MicroPython and CPython,
19+
keeping code compatible with the two interpreters.
20+
21+
`__reduce__` and `__reduce_ex__` will be used in MicroPython if a class
22+
provides them, but unless you're also planning to use object pickling,
23+
`__copy__` and `__deepcopy__` are the simplest way to make sure things work in
24+
all cases.

0 commit comments

Comments
 (0)