summaryrefslogtreecommitdiffstatshomepage
path: root/docs/library
diff options
context:
space:
mode:
authorDamien George <damien.p.george@gmail.com>2017-08-30 11:04:47 +1000
committerDamien George <damien.p.george@gmail.com>2017-08-30 11:04:47 +1000
commitc7d334e047ce5a36bd6d4979a5331719dd480a2b (patch)
tree3dbb206e3075eb5f1778389f1399c28d3fd88d34 /docs/library
parent25e24b2c3c63e035b4c145f743f5cd7b02a23fc0 (diff)
parent1f78e7a43130acfa4bedf16c1007a1b0f37c75c3 (diff)
downloadmicropython-c7d334e047ce5a36bd6d4979a5331719dd480a2b.tar.gz
micropython-c7d334e047ce5a36bd6d4979a5331719dd480a2b.zip
Merge tag 'v1.9.2' into parse-bytecode
Double precision math library and support on pyboard, and improved ussl This release brings general improvements and bug fixes to the core and various ports, as well as documentation additions, clean-ups and better consistency. And effort has been made to clean up the source code to make it more consistent across the core and all ports. There is a new tool "mpy_bin2res.py" to convert arbitrary (binary) files to Python resources for inclusion in source code (frozen or otherwise). The ussl module has seen improvements, including implementation of server_hostname (for axtls) and server_side mode (for mbedtls). There is now a double-precision float math library and stmhal has support to build firmware with software or hardware double-precision. A detailed list of changes follows. py core: - formatfloat: fix number of digits and exponent sign when rounding - modthread: raise RuntimeError in release() if lock is not acquired - compile: raise SyntaxError if positional args are given after */** - objint: support "big" byte-order in int.to_bytes() - objint: in to_bytes(), allow length arg to be any int and check sign - compile: fix bug with break/continue in else of optimised for-range - compile: optimise emitter label indices to save a word of heap - builtinimport: remove unreachable code for relative imports - objnamedtuple: simplify and remove use of alloca building namedtuple - mpprint: remove unreachable check for neg return of mp_format_float - binary: add missing "break" statements - runtime: mark m_malloc_fail() as NORETURN - objstr: remove unnecessary "sign" variable in formatting code - vm: make "if" control flow more obvious in YIELD_FROM opcode - modmath: check for zero division in log with 2 args - makeversionhdr.py: update to parse new release line in docs/conf.py - objdict: factorise dict accessor helper to reduce code size - change mp_uint_t to size_t in builtins code - repl: change mp_uint_t to size_t in repl helpers - compile: combine arith and bit-shift ops into 1 compile routine - compile: use switch-case to match token and operator - objgenerator: allow to hash generators and generator instances - gc: refactor assertions in gc_free function - vm: make n_state variable local to just set-up part of VM - asmx64: support moving a 64-bit immediate to one of top 8 registers - modmicropython: cast stack_limit value so it prints correctly - builtinevex: add typechecking of globals/locals args to eval/exec - py.mk: make berkeley-db C-defs apply only to relevant source files - mperrno: allow mperrno.h to be correctly included before other hdrs - mpz: make mpz_is_zero() an inline function - implement raising a big-int to a negative power - mkrules.mk: show frozen modules sizes together with executable size - objtuple: allow to use inplace-multiplication operator on tuples - objstr: raise an exception for wrong type on RHS of str binary op - modsys: initial implementation of sys.getsizeof() - binary.c: fix bug when packing big-endian 'Q' values - add verbose debug compile-time flag MICROPY_DEBUG_VERBOSE - binary: change internal bytearray typecode from 0 to 1 - objstringio: prevent offset wraparound for io.BytesIO objects - objstringio: fix regression with handling SEEK_SET - stream: seek: Consistently handle negative offset for SEEK_SET - mkrules.mk: use "find -path" when searching for frozen obj files - compile: remove unused pn_colon code when compiling func params - objcomplex: remove unnecessary assignment of variable - formatfloat: don't post-increment variable that won't be used again - use "static inline" for funcs that should be inline - asmthumb: use existing macro to properly clear the D-cache extmod: - modussl_axtls: update for axTLS 2.1.3 - modussl_axtls: implement server_hostname arg to wrap_socket() - move modonewire.c from esp8266 to extmod directory - modure: if input string is bytes, return bytes results too - modubinascii: add check for empty buffer passed to hexlify - modussl_axtls: allow to close ssl stream multiple times - modussl_mbedtls: support server_side mode - modussl_mbedtls: when reading and peer wants to close, return 0 - modframebuf: fix invalid stride for odd widths in GS4_HMSB fmt - modussl_mbedtls: make socket.close() free all TLS resources - modframebuf: consistently use "col" as name for colour variables - modussl_mbedtls: implement non-blocking SSL sockets - machine_signal: fix parsing of invert arg when Pin is first arg - modframebuf: use correct initialization for .locals_dict - modlwip: implement setsockopt(IP_ADD_MEMBERSHIP) - modussl_mbedtls.c: add ussl.getpeercert() method - modubinascii: rewrite mod_binascii_a2b_base64 - modubinascii: don't post-increment variable that won't be used - modonewire: rename public module to mp_module_onewire - for uos.stat interpret st_size member as an unsigned int - use "static inline" for funcs that should be inline lib: - axtls: upgrade to axTLS 2.1.3 + MicroPython patchset - libm/math: remove implementations of float conversion functions - add libm_dbl, a double-precision math library, from musl-1.1.16 drivers: - onewire: move onewire.py, ds18x20.py from esp8266 to drivers - onewire: enable pull-up when init'ing the 1-wire pin tools: - gen-cpydiff: use case description as 3rd-level heading - pyboard: add license header - mpy_bin2res: tools to convert binary resources to Python module - mpy-tool.py: don't generate const_table if it's empty - mpy-tool.py: fix missing argument in dump() function tests: - net_inet/test_tls_sites.py: integration test for SSL connections - net_inet: add tests for accept and connect in nonblocking mode - basics: add tests for for-else statement - net_inet: move tests which don't require full Internet to net_hosted - connect_nonblock: refactor towards real net_hosted test - auto detect floating point capabilites of the target - import: add a test for the builtin __import__ function - import: update comment now that uPy raises correct exception - basics/namedtuple1: add test for creating with pos and kw args - unix/extra_coverage: add test for mp_vprintf with bad fmt spec - basics: add tests for arithmetic operators precedence - cpydiff/modules_deque: elaborate workaround - cpydiff/core_class_mro: move under Classes, add workaround - cpydiff/core_arguments: move under Functions subsection - cpydiff/core_class_supermultiple: same cause as core_class_mro - cpydiff: improve wording, add more workarounds - cpydiff: add case for str.ljust/rjust - rename exec1.py to builtin_exec.py - basics/builtin_exec: test various globals/locals args to exec() minimal port: - Makefile: enable gc-sections to remove unused code - remove unused stmhal include from Makefile - use size_t for mp_builtin_open argument unix port: - modtime: replace strftime() with localtime() - mpconfigport.mk: update descriptions of readline and TLS options - Makefile: disable assertions in the standard unix executable - modjni: convert to mp_rom_map_elem_t - for uos.stat interpret st_size member as an unsigned int stmhal port: - mpconfigport.h: remove config of PY_THREAD_GIL to use default - make error messages more consistent across peripherals - add initial implementation of Pin.irq() method - add .value() method to Switch object, to mirror Pin and Signal - move pybstdio.c to lib/utils/sys_stdio_mphal.c for common use - add "quiet timing" enter/exit functions - make available the _onewire module, for low-level bus control - modules: provide sym-link to onewire.py driver - boards/stm32f405.ld: increase FLASH_TEXT to end of 1MiB flash - sdcard: allow a board to customise the SDIO pins - add possibility to build with double-precision floating point - boards: enable double-prec FP on F76x boards - Makefile: use hardware double-prec FP for MCUs that support it - Makefile: rename FLOAT_IMPL to MICROPY_FLOAT_IMPL to match C name - Makefile: add CFLAGS_EXTRA to CFLAGS so cmdline can add options - mpconfigport.h: allow MICROPY_PY_THREAD to be overridden - boards: add configuration files for NUCLEO_F429ZI - boards/NUCLEO_F429ZI: change USB config from HS to FS peripheral - reduce size of ESPRUINO_PICO build so it fits in flash - servo: make pyb.Servo(n) map to Pin('Xn') on all MCUs - servo: don't compile servo code when it's not enabled - use "static inline" for funcs that should be inline cc3200 port: - modusocket: simplify socket.makefile() function - make non-zero socket timeout work with connect/accept/send - modusocket: fix connect() when in non-blocking or timeout mode - use the name MicroPython consistently in code esp8266 port: - Makefile: bump axTLS TLS record buffer size to 5K - Makefile: allow FROZEN_DIR,FROZEN_MPY_DIR to be overridden - Makefile: add LIB_SRC_C variable to qstr auto-extraction list - make onewire module and support code usable by other ports - modonewire: move low-level 1-wire bus code to modonewire.c - modonewire: make timings static and remove onewire.timings func - reinstate 1-wire scripts by sym-linking to drivers/onewire/ - move mp_hal_pin_open_drain from esp_mphal.c to machine_pin.c - enable MICROPY_ENABLE_FINALISER - README: make "Documentation" a top-level section - machine_rtc: use correct arithmetic for aligning RTC mem len - mpconfigport_512k: use terse error messages to get 512k to fit - mpconfigport.h: make socket a weak link - modesp: remove unused constants: STA_MODE, etc - general: add known issue of WiFi RX buffers overflow - use size_t for mp_builtin_open argument - fix UART stop bit constants zephyr port: - Makefile: rework dependencies and "clean" target - Makefile: revert prj.conf construction rule to the previous state - remove long-obsolete machine_ptr_t typedef's - Makefile: explicitly define default target as "all" - modusocket: allow to use socketized net_context in upstream - modusocket: socket, close: switch to native Zephyr socket calls - modusocket: bind, connect, listen, accept: Swtich to native sockets - modusocket: send: switch to native sockets - modusocket: recv: switch to native sockets - modusocket: fully switch to native Zephyr sockets - modzephyr: add current_tid() and stacks_analyze() functions - prj_base.conf: enable CONFIG_INIT_STACKS - modusocket: update struct sockaddr family field name - prj_96b_carbon.conf: re-enable networking on Carbon - modzephyr: add shell_net_iface() function docs: - btree: add hints about opening db file and need to flush db - select: rename to uselect, to match the actual module name - license: update copyright year - esp8266/tutorial/intro: discourage use of 512kb firmwares - esp8266/tutorial/intro: Sphinx requires blank lines around literal blocks - conf.py: include 3 levels of ToC in latexpdf output - gc: mark mem_alloc()/mem_free() as uPy-specific - gc: document gc.threshold() function - builtins: list builtin exceptions - conf.py: set default_role = 'any' - lcd160cr: group related constants together and use full sentences - ref/speed_python: update and make more hardware-neutral - library/gc: fix grammar and improve readability of gc.threshold() - move all ports docs to the single ToC - topindex.html: remove link to wipy.io, it's no longer available - conf.py: add .venv dir to exclude_patterns - move topindex.html to templates/ subdir - differences/index_template: use consistent heading casing - builtins: add AssertionError, SyntaxError, ZeroDivisionError - add glossary - conf.py: switch to "new" format of intersphinx_mapping - conf.py: add file for global replacements definition - library: add CPython docs xref to each pertinent module - replace.inc: add |see_cpython|, to xref individual symbols from CPython - conf.py: set "version" and "release" to the same value - *_index: drop "Indices and tables" pseudo-section - pyboard: move hardware info into General Info chapter - uerrno: document "uerrno" module - esp8266/general.rst: fix name of NTP module - pyboard: move info about using Windows from topindex to general - uzlib: update description of decompress() and mention DecompIO - pyboard/tutorial/amp_skin: add example for playing large WAV files - library/ubinascii: update base64 docs - library/usocket: move socket.error to its own section - library/usocket: describe complete information on address formats - glossary: elaborate on possible MicroPython port differences - glossary: fix typos in micropython-lib paragraph - index: rewrite introduction paragraph to avoid confusion - use the name MicroPython consistently in documentation - consistently link to micropython-lib in glossary all: - make more use of mp_raise_{msg,TypeError,ValueError} helpers - unify header guard usage - remove trailing spaces, per coding conventions - don't include system errno.h when it's not needed - use the name MicroPython consistently in comments - make use of $(TOP) variable in Makefiles, instead of ".." - raise exceptions via mp_raise_XXX - make static dicts use mp_rom_map_elem_t type and MP_ROM_xxx macros README: - mention support for bytecode and frozen bytecode - improve description of precompiled bytecode; mention mpy-cross CODECONVENTIONS: - clarify MicroPython changes sign-off process - start to describe docs conventions - describe docs use of markup for None/True/False travis: - build STM32F769DISC board instead of F7DISC to test dbl-prec FP - pin cpp-coveralls at 0.3.12
Diffstat (limited to 'docs/library')
-rw-r--r--docs/library/array.rst3
-rw-r--r--docs/library/btree.rst53
-rw-r--r--docs/library/builtins.rst61
-rw-r--r--docs/library/cmath.rst2
-rw-r--r--docs/library/esp.rst14
-rw-r--r--docs/library/framebuf.rst24
-rw-r--r--docs/library/gc.rst39
-rw-r--r--docs/library/index.rst17
-rw-r--r--docs/library/lcd160cr.rst126
-rw-r--r--docs/library/machine.I2C.rst70
-rw-r--r--docs/library/machine.RTC.rst2
-rw-r--r--docs/library/machine.UART.rst2
-rw-r--r--docs/library/machine.rst28
-rw-r--r--docs/library/math.rst2
-rw-r--r--docs/library/micropython.rst20
-rw-r--r--docs/library/network.rst52
-rw-r--r--docs/library/pyb.Switch.rst7
-rw-r--r--docs/library/pyb.rst8
-rw-r--r--docs/library/sys.rst24
-rw-r--r--docs/library/ubinascii.rst12
-rw-r--r--docs/library/ucollections.rst2
-rw-r--r--docs/library/uerrno.rst34
-rw-r--r--docs/library/uhashlib.rst2
-rw-r--r--docs/library/uheapq.rst2
-rw-r--r--docs/library/uio.rst2
-rw-r--r--docs/library/ujson.rst2
-rw-r--r--docs/library/uos.rst14
-rw-r--r--docs/library/ure.rst41
-rw-r--r--docs/library/uselect.rst (renamed from docs/library/select.rst)45
-rw-r--r--docs/library/usocket.rst154
-rw-r--r--docs/library/ussl.rst6
-rw-r--r--docs/library/ustruct.rst19
-rw-r--r--docs/library/utime.rst82
-rw-r--r--docs/library/uzlib.rst30
34 files changed, 633 insertions, 368 deletions
diff --git a/docs/library/array.rst b/docs/library/array.rst
index f52b4b385e..d096c6ec48 100644
--- a/docs/library/array.rst
+++ b/docs/library/array.rst
@@ -4,8 +4,7 @@
.. module:: array
:synopsis: efficient arrays of numeric data
-See `Python array <https://docs.python.org/3/library/array.html>`_ for more
-information.
+|see_cpython_module| :mod:`python:array`.
Supported format codes: ``b``, ``B``, ``h``, ``H``, ``i``, ``I``, ``l``,
``L``, ``q``, ``Q``, ``f``, ``d`` (the latter 2 depending on the
diff --git a/docs/library/btree.rst b/docs/library/btree.rst
index bd7890586a..9322d32e6a 100644
--- a/docs/library/btree.rst
+++ b/docs/library/btree.rst
@@ -22,8 +22,14 @@ Example::
# First, we need to open a stream which holds a database
# This is usually a file, but can be in-memory database
- # using uio.BytesIO, a raw flash section, etc.
- f = open("mydb", "w+b")
+ # using uio.BytesIO, a raw flash partition, etc.
+ # Oftentimes, you want to create a database file if it doesn't
+ # exist and open if it exists. Idiom below takes care of this.
+ # DO NOT open database with "a+b" access mode.
+ try:
+ f = open("mydb", "r+b")
+ except OSError:
+ f = open("mydb", "w+b")
# Now open a database itself
db = btree.open(f)
@@ -33,6 +39,11 @@ Example::
db[b"1"] = b"one"
db[b"2"] = b"two"
+ # Assume that any changes are cached in memory unless
+ # explicitly flushed (or database closed). Flush database
+ # at the end of each "transaction".
+ db.flush()
+
# Prints b'two'
print(db[b"2"])
@@ -71,18 +82,18 @@ Functions
other parameters are optional and keyword-only, and allow to tweak advanced
parameters of the database operation (most users will not need them):
- * `flags` - Currently unused.
- * `cachesize` - Suggested maximum memory cache size in bytes. For a
+ * *flags* - Currently unused.
+ * *cachesize* - Suggested maximum memory cache size in bytes. For a
board with enough memory using larger values may improve performance.
The value is only a recommendation, the module may use more memory if
values set too low.
- * `pagesize` - Page size used for the nodes in BTree. Acceptable range
+ * *pagesize* - Page size used for the nodes in BTree. Acceptable range
is 512-65536. If 0, underlying I/O block size will be used (the best
compromise between memory usage and performance).
- * `minkeypage` - Minimum number of keys to store per page. Default value
+ * *minkeypage* - Minimum number of keys to store per page. Default value
of 0 equivalent to 2.
- Returns a `BTree` object, which implements a dictionary protocol (set
+ Returns a BTree object, which implements a dictionary protocol (set
of methods), and some additional methods described below.
Methods
@@ -92,7 +103,7 @@ Methods
Close the database. It's mandatory to close the database at the end of
processing, as some unwritten data may be still in the cache. Note that
- this does not close underlying streamw with which the database was opened,
+ this does not close underlying stream with which the database was opened,
it should be closed separately (which is also mandatory to make sure that
data flushed from buffer to the underlying storage).
@@ -101,10 +112,10 @@ Methods
Flush any data in cache to the underlying stream.
.. method:: btree.__getitem__(key)
-.. method:: btree.get(key, default=None)
-.. method:: btree.__setitem__(key, val)
-.. method:: btree.__detitem__(key)
-.. method:: btree.__contains__(key)
+ btree.get(key, default=None)
+ btree.__setitem__(key, val)
+ btree.__detitem__(key)
+ btree.__contains__(key)
Standard dictionary methods.
@@ -114,20 +125,20 @@ Methods
to get access to all keys in order.
.. method:: btree.keys([start_key, [end_key, [flags]]])
-.. method:: btree.values([start_key, [end_key, [flags]]])
-.. method:: btree.items([start_key, [end_key, [flags]]])
+ btree.values([start_key, [end_key, [flags]]])
+ btree.items([start_key, [end_key, [flags]]])
These methods are similar to standard dictionary methods, but also can
take optional parameters to iterate over a key sub-range, instead of
- the entire database. Note that for all 3 methods, `start_key` and
- `end_key` arguments represent key values. For example, ``values()``
+ the entire database. Note that for all 3 methods, *start_key* and
+ *end_key* arguments represent key values. For example, `values()`
method will iterate over values corresponding to they key range
- given. None values for `start_key` means "from the first key", no
- `end_key` or its value of None means "until the end of database".
- By default, range is inclusive of `start_key` and exclusive of
- `end_key`, you can include `end_key` in iteration by passing `flags`
+ given. None values for *start_key* means "from the first key", no
+ *end_key* or its value of None means "until the end of database".
+ By default, range is inclusive of *start_key* and exclusive of
+ *end_key*, you can include *end_key* in iteration by passing *flags*
of `btree.INCL`. You can iterate in descending key direction
- by passing `flags` of `btree.DESC`. The flags values can be ORed
+ by passing *flags* of `btree.DESC`. The flags values can be ORed
together.
Constants
diff --git a/docs/library/builtins.rst b/docs/library/builtins.rst
index 46f762660a..365248dc76 100644
--- a/docs/library/builtins.rst
+++ b/docs/library/builtins.rst
@@ -1,8 +1,11 @@
-Builtin Functions
-=================
+Builtin functions and exceptions
+================================
-All builtin functions are described here. They are also available via
-``builtins`` module.
+All builtin functions and exceptions are described here. They are also
+available via ``builtins`` module.
+
+Functions and types
+-------------------
.. function:: abs()
@@ -18,6 +21,8 @@ All builtin functions are described here. They are also available via
.. class:: bytes()
+ |see_cpython| `python:bytes`.
+
.. function:: callable()
.. function:: chr()
@@ -144,3 +149,51 @@ All builtin functions are described here. They are also available via
.. function:: type()
.. function:: zip()
+
+
+Exceptions
+----------
+
+.. exception:: AssertionError
+
+.. exception:: AttributeError
+
+.. exception:: Exception
+
+.. exception:: ImportError
+
+.. exception:: IndexError
+
+.. exception:: KeyboardInterrupt
+
+.. exception:: KeyError
+
+.. exception:: MemoryError
+
+.. exception:: NameError
+
+.. exception:: NotImplementedError
+
+.. exception:: OSError
+
+ |see_cpython| `python:OSError`. MicroPython doesn't implement ``errno``
+ attribute, instead use the standard way to access exception arguments:
+ ``exc.args[0]``.
+
+.. exception:: RuntimeError
+
+.. exception:: StopIteration
+
+.. exception:: SyntaxError
+
+.. exception:: SystemExit
+
+ |see_cpython| `python:SystemExit`.
+
+.. exception:: TypeError
+
+ |see_cpython| `python:TypeError`.
+
+.. exception:: ValueError
+
+.. exception:: ZeroDivisionError
diff --git a/docs/library/cmath.rst b/docs/library/cmath.rst
index 465cf54ad3..59e4ec1722 100644
--- a/docs/library/cmath.rst
+++ b/docs/library/cmath.rst
@@ -4,6 +4,8 @@
.. module:: cmath
:synopsis: mathematical functions for complex numbers
+|see_cpython_module| :mod:`python:cmath`.
+
The ``cmath`` module provides some basic mathematical functions for
working with complex numbers.
diff --git a/docs/library/esp.rst b/docs/library/esp.rst
index 8cafb92cd0..121a80d42e 100644
--- a/docs/library/esp.rst
+++ b/docs/library/esp.rst
@@ -14,7 +14,7 @@ Functions
Get or set the sleep type.
- If the ``sleep_type`` parameter is provided, sets the sleep type to its
+ If the *sleep_type* parameter is provided, sets the sleep type to its
value. If the function is called without parameters, returns the current
sleep type.
@@ -55,23 +55,23 @@ Functions
1MByte of flash (which is memory mapped), and this function controls the
location.
- If `start` and `length` are both `None` then the native code location is
+ If *start* and *length* are both ``None`` then the native code location is
set to the unused portion of memory at the end of the iRAM1 region. The
size of this unused portion depends on the firmware and is typically quite
small (around 500 bytes), and is enough to store a few very small
functions. The advantage of using this iRAM1 region is that it does not
get worn out by writing to it.
- If neither `start` nor `length` are `None` then they should be integers.
- `start` should specify the byte offset from the beginning of the flash at
- which native code should be stored. `length` specifies how many bytes of
- flash from `start` can be used to store native code. `start` and `length`
+ If neither *start* nor *length* are ``None`` then they should be integers.
+ *start* should specify the byte offset from the beginning of the flash at
+ which native code should be stored. *length* specifies how many bytes of
+ flash from *start* can be used to store native code. *start* and *length*
should be multiples of the sector size (being 4096 bytes). The flash will
be automatically erased before writing to it so be sure to use a region of
flash that is not otherwise used, for example by the firmware or the
filesystem.
- When using the flash to store native code `start+length` must be less
+ When using the flash to store native code *start+length* must be less
than or equal to 1MByte. Note that the flash can be worn out if repeated
erasures (and writes) are made so use this feature sparingly.
In particular, native code needs to be recompiled and rewritten to flash
diff --git a/docs/library/framebuf.rst b/docs/library/framebuf.rst
index 61f0635f36..b92bd08eff 100644
--- a/docs/library/framebuf.rst
+++ b/docs/library/framebuf.rst
@@ -32,25 +32,25 @@ Constructors
Construct a FrameBuffer object. The parameters are:
- - `buffer` is an object with a buffer protocol which must be large
+ - *buffer* is an object with a buffer protocol which must be large
enough to contain every pixel defined by the width, height and
format of the FrameBuffer.
- - `width` is the width of the FrameBuffer in pixels
- - `height` is the height of the FrameBuffer in pixels
- - `format` specifies the type of pixel used in the FrameBuffer;
+ - *width* is the width of the FrameBuffer in pixels
+ - *height* is the height of the FrameBuffer in pixels
+ - *format* specifies the type of pixel used in the FrameBuffer;
valid values are ``framebuf.MVLSB``, ``framebuf.RGB565``
and ``framebuf.GS4_HMSB``. MVLSB is monochrome 1-bit color,
RGB565 is RGB 16-bit color, and GS4_HMSB is grayscale 4-bit color.
Where a color value c is passed to a method, c is a small integer
with an encoding that is dependent on the format of the FrameBuffer.
- - `stride` is the number of pixels between each horizontal line
- of pixels in the FrameBuffer. This defaults to `width` but may
+ - *stride* is the number of pixels between each horizontal line
+ of pixels in the FrameBuffer. This defaults to *width* but may
need adjustments when implementing a FrameBuffer within another
- larger FrameBuffer or screen. The `buffer` size must accommodate
+ larger FrameBuffer or screen. The *buffer* size must accommodate
an increased step size.
- One must specify valid `buffer`, `width`, `height`, `format` and
- optionally `stride`. Invalid `buffer` size or dimensions may lead to
+ One must specify valid *buffer*, *width*, *height*, *format* and
+ optionally *stride*. Invalid *buffer* size or dimensions may lead to
unexpected errors.
Drawing primitive shapes
@@ -64,8 +64,8 @@ The following methods draw shapes onto the FrameBuffer.
.. method:: FrameBuffer.pixel(x, y[, c])
- If `c` is not given, get the color value of the specified pixel.
- If `c` is given, set the specified pixel to the given color.
+ If *c* is not given, get the color value of the specified pixel.
+ If *c* is given, set the specified pixel to the given color.
.. method:: FrameBuffer.hline(x, y, w, c)
.. method:: FrameBuffer.vline(x, y, h, c)
@@ -106,7 +106,7 @@ Other methods
.. method:: FrameBuffer.blit(fbuf, x, y[, key])
Draw another FrameBuffer on top of the current one at the given coordinates.
- If `key` is specified then it should be a color integer and the
+ If *key* is specified then it should be a color integer and the
corresponding color will be considered transparent: all pixels with that
color value will not be drawn.
diff --git a/docs/library/gc.rst b/docs/library/gc.rst
index 01e63ae51e..c823aed3e6 100644
--- a/docs/library/gc.rst
+++ b/docs/library/gc.rst
@@ -4,6 +4,8 @@
.. module:: gc
:synopsis: control the garbage collector
+|see_cpython_module| :mod:`python:gc`.
+
Functions
---------
@@ -24,6 +26,41 @@ Functions
Return the number of bytes of heap RAM that are allocated.
+ .. admonition:: Difference to CPython
+ :class: attention
+
+ This function is MicroPython extension.
+
.. function:: mem_free()
- Return the number of bytes of available heap RAM.
+ Return the number of bytes of available heap RAM, or -1 if this amount
+ is not known.
+
+ .. admonition:: Difference to CPython
+ :class: attention
+
+ This function is MicroPython extension.
+
+.. function:: threshold([amount])
+
+ Set or query the additional GC allocation threshold. Normally, a collection
+ is triggered only when a new allocation cannot be satisfied, i.e. on an
+ out-of-memory (OOM) condition. If this function is called, in addition to
+ OOM, a collection will be triggered each time after *amount* bytes have been
+ allocated (in total, since the previous time such an amount of bytes
+ have been allocated). *amount* is usually specified as less than the
+ full heap size, with the intention to trigger a collection earlier than when the
+ heap becomes exhausted, and in the hope that an early collection will prevent
+ excessive memory fragmentation. This is a heuristic measure, the effect
+ of which will vary from application to application, as well as
+ the optimal value of the *amount* parameter.
+
+ Calling the function without argument will return the current value of
+ the threshold. A value of -1 means a disabled allocation threshold.
+
+ .. admonition:: Difference to CPython
+ :class: attention
+
+ This function is a MicroPython extension. CPython has a similar
+ function - ``set_threshold()``, but due to different GC
+ implementations, its signature and semantics are different.
diff --git a/docs/library/index.rst b/docs/library/index.rst
index 770920a1ff..0789ea43d9 100644
--- a/docs/library/index.rst
+++ b/docs/library/index.rst
@@ -1,3 +1,5 @@
+.. _micropython_lib:
+
MicroPython libraries
=====================
@@ -38,8 +40,7 @@ information pertaining to a specific port.
Beyond the built-in libraries described in this documentation, many more
modules from the Python standard library, as well as further MicroPython
-extensions to it, can be found in the `micropython-lib repository
-<https://github.com/micropython/micropython-lib>`_.
+extensions to it, can be found in `micropython-lib`.
Python standard libraries and micro-libraries
---------------------------------------------
@@ -52,7 +53,7 @@ e.g. ``ujson`` instead of ``json``. This is to signify that such a module is
micro-library, i.e. implements only a subset of CPython module functionality.
By naming them differently, a user has a choice to write a Python-level module
to extend functionality for better compatibility with CPython (indeed, this is
-what done by micropython-lib project mentioned above).
+what done by the `micropython-lib` project mentioned above).
On some embedded platforms, where it may be cumbersome to add Python-level
wrapper modules to achieve naming compatibility with CPython, micro-modules
@@ -72,16 +73,17 @@ it will fallback to loading the built-in ``ujson`` module.
cmath.rst
gc.rst
math.rst
- select.rst
sys.rst
ubinascii.rst
ucollections.rst
+ uerrno.rst
uhashlib.rst
uheapq.rst
uio.rst
ujson.rst
uos.rst
ure.rst
+ uselect.rst
usocket.rst
ustruct.rst
utime.rst
@@ -97,16 +99,17 @@ it will fallback to loading the built-in ``ujson`` module.
cmath.rst
gc.rst
math.rst
- select.rst
sys.rst
ubinascii.rst
ucollections.rst
+ uerrno.rst
uhashlib.rst
uheapq.rst
uio.rst
ujson.rst
uos.rst
ure.rst
+ uselect.rst
usocket.rst
ustruct.rst
utime.rst
@@ -120,12 +123,12 @@ it will fallback to loading the built-in ``ujson`` module.
builtins.rst
array.rst
gc.rst
- select.rst
sys.rst
ubinascii.rst
ujson.rst
uos.rst
ure.rst
+ uselect.rst
usocket.rst
ussl.rst
utime.rst
@@ -142,12 +145,14 @@ it will fallback to loading the built-in ``ujson`` module.
sys.rst
ubinascii.rst
ucollections.rst
+ uerrno.rst
uhashlib.rst
uheapq.rst
uio.rst
ujson.rst
uos.rst
ure.rst
+ uselect.rst
usocket.rst
ussl.rst
ustruct.rst
diff --git a/docs/library/lcd160cr.rst b/docs/library/lcd160cr.rst
index bd47412986..567994640b 100644
--- a/docs/library/lcd160cr.rst
+++ b/docs/library/lcd160cr.rst
@@ -41,21 +41,21 @@ Constructors
Construct an LCD160CR object. The parameters are:
- - `connect` is a string specifying the physical connection of the LCD
+ - *connect* is a string specifying the physical connection of the LCD
display to the board; valid values are "X", "Y", "XY", "YX".
Use "X" when the display is connected to a pyboard in the X-skin
position, and "Y" when connected in the Y-skin position. "XY"
and "YX" are used when the display is connected to the right or
left side of the pyboard, respectively.
- - `pwr` is a Pin object connected to the LCD's power/enabled pin.
- - `i2c` is an I2C object connected to the LCD's I2C interface.
- - `spi` is an SPI object connected to the LCD's SPI interface.
- - `i2c_addr` is the I2C address of the display.
-
- One must specify either a valid `connect` or all of `pwr`, `i2c` and `spi`.
- If a valid `connect` is given then any of `pwr`, `i2c` or `spi` which are
- not passed as parameters (ie they are `None`) will be created based on the
- value of `connect`. This allows to override the default interface to the
+ - *pwr* is a Pin object connected to the LCD's power/enabled pin.
+ - *i2c* is an I2C object connected to the LCD's I2C interface.
+ - *spi* is an SPI object connected to the LCD's SPI interface.
+ - *i2c_addr* is the I2C address of the display.
+
+ One must specify either a valid *connect* or all of *pwr*, *i2c* and *spi*.
+ If a valid *connect* is given then any of *pwr*, *i2c* or *spi* which are
+ not passed as parameters (i.e. they are ``None``) will be created based on the
+ value of *connect*. This allows to override the default interface to the
display if needed.
The default values are:
@@ -103,12 +103,12 @@ Setup commands
.. method:: LCD160CR.set_power(on)
- Turn the display on or off, depending on the given value of `on`: 0 or `False`
- will turn the display off, and 1 or `True` will turn it on.
+ Turn the display on or off, depending on the given value of *on*: 0 or ``False``
+ will turn the display off, and 1 or ``True`` will turn it on.
.. method:: LCD160CR.set_orient(orient)
- Set the orientation of the display. The `orient` parameter can be one
+ Set the orientation of the display. The *orient* parameter can be one
of `PORTRAIT`, `LANDSCAPE`, `PORTRAIT_UPSIDEDOWN`, `LANDSCAPE_UPSIDEDOWN`.
.. method:: LCD160CR.set_brightness(value)
@@ -117,7 +117,7 @@ Setup commands
.. method:: LCD160CR.set_i2c_addr(addr)
- Set the I2C address of the display. The `addr` value must have the
+ Set the I2C address of the display. The *addr* value must have the
lower 2 bits cleared.
.. method:: LCD160CR.set_uart_baudrate(baudrate)
@@ -126,7 +126,7 @@ Setup commands
.. method:: LCD160CR.set_startup_deco(value)
- Set the start-up decoration of the display. The `value` parameter can be a
+ Set the start-up decoration of the display. The *value* parameter can be a
logical or of `STARTUP_DECO_NONE`, `STARTUP_DECO_MLOGO`, `STARTUP_DECO_INFO`.
.. method:: LCD160CR.save_to_flash()
@@ -151,17 +151,17 @@ The following methods manipulate individual pixels on the display.
.. method:: LCD160CR.get_line(x, y, buf)
Low-level method to get a line of pixels into the given buffer.
- To read `n` pixels `buf` should be `2*n+1` bytes in length. The first byte
+ To read *n* pixels *buf* should be *2*n+1* bytes in length. The first byte
is a dummy byte and should be ignored, and subsequent bytes represent the
- pixels in the line starting at coordinate `(x, y)`.
+ pixels in the line starting at coordinate *(x, y)*.
.. method:: LCD160CR.screen_dump(buf, x=0, y=0, w=None, h=None)
- Dump the contents of the screen to the given buffer. The parameters `x` and `y`
- specify the starting coordinate, and `w` and `h` the size of the region. If `w`
- or `h` are `None` then they will take on their maximum values, set by the size
- of the screen minus the given `x` and `y` values. `buf` should be large enough
- to hold `2*w*h` bytes. If it's smaller then only the initial horizontal lines
+ Dump the contents of the screen to the given buffer. The parameters *x* and *y*
+ specify the starting coordinate, and *w* and *h* the size of the region. If *w*
+ or *h* are ``None`` then they will take on their maximum values, set by the size
+ of the screen minus the given *x* and *y* values. *buf* should be large enough
+ to hold ``2*w*h`` bytes. If it's smaller then only the initial horizontal lines
will be stored.
.. method:: LCD160CR.screen_load(buf)
@@ -188,18 +188,18 @@ To draw text one sets the position, color and font, and then uses
Set the font for the text. Subsequent calls to `write` will use the newly
configured font. The parameters are:
- - `font` is the font family to use, valid values are 0, 1, 2, 3.
- - `scale` is a scaling value for each character pixel, where the pixels
- are drawn as a square with side length equal to `scale + 1`. The value
+ - *font* is the font family to use, valid values are 0, 1, 2, 3.
+ - *scale* is a scaling value for each character pixel, where the pixels
+ are drawn as a square with side length equal to *scale + 1*. The value
can be between 0 and 63.
- - `bold` controls the number of pixels to overdraw each character pixel,
- making a bold effect. The lower 2 bits of `bold` are the number of
+ - *bold* controls the number of pixels to overdraw each character pixel,
+ making a bold effect. The lower 2 bits of *bold* are the number of
pixels to overdraw in the horizontal direction, and the next 2 bits are
- for the vertical direction. For example, a `bold` value of 5 will
+ for the vertical direction. For example, a *bold* value of 5 will
overdraw 1 pixel in both the horizontal and vertical directions.
- - `trans` can be either 0 or 1 and if set to 1 the characters will be
+ - *trans* can be either 0 or 1 and if set to 1 the characters will be
drawn with a transparent background.
- - `scroll` can be either 0 or 1 and if set to 1 the display will do a
+ - *scroll* can be either 0 or 1 and if set to 1 the display will do a
soft scroll if the text moves to the next line.
.. method:: LCD160CR.write(s)
@@ -252,7 +252,7 @@ Primitive drawing commands use a foreground and background color set by the
.. method:: LCD160CR.poly_dot(data)
Draw a sequence of dots using the pen line color.
- The `data` should be a buffer of bytes, with each successive pair of
+ The *data* should be a buffer of bytes, with each successive pair of
bytes corresponding to coordinate pairs (x, y).
.. method:: LCD160CR.poly_line(data)
@@ -266,25 +266,25 @@ Touch screen methods
Configure the touch panel:
- - If `calib` is `True` then the call will trigger a touch calibration of
+ - If *calib* is ``True`` then the call will trigger a touch calibration of
the resistive touch sensor. This requires the user to touch various
parts of the screen.
- - If `save` is `True` then the touch parameters will be saved to NVRAM
+ - If *save* is ``True`` then the touch parameters will be saved to NVRAM
to persist across reset/power up.
- - If `irq` is `True` then the display will be configured to pull the IRQ
- line low when a touch force is detected. If `irq` is `False` then this
- feature is disabled. If `irq` is `None` (the default value) then no
+ - If *irq* is ``True`` then the display will be configured to pull the IRQ
+ line low when a touch force is detected. If *irq* is ``False`` then this
+ feature is disabled. If *irq* is ``None`` (the default value) then no
change is made to this setting.
.. method:: LCD160CR.is_touched()
- Returns a boolean: `True` if there is currently a touch force on the screen,
+ Returns a boolean: ``True`` if there is currently a touch force on the screen,
`False` otherwise.
.. method:: LCD160CR.get_touch()
- Returns a 3-tuple of: (active, x, y). If there is currently a touch force
- on the screen then `active` is 1, otherwise it is 0. The `x` and `y` values
+ Returns a 3-tuple of: *(active, x, y)*. If there is currently a touch force
+ on the screen then *active* is 1, otherwise it is 0. The *x* and *y* values
indicate the position of the current or most recent touch.
Advanced commands
@@ -308,7 +308,7 @@ Advanced commands
.. method:: LCD160CR.show_framebuf(buf)
- Show the given buffer on the display. `buf` should be an array of bytes containing
+ Show the given buffer on the display. *buf* should be an array of bytes containing
the 16-bit RGB values for the pixels, and they will be written to the area
specified by :meth:`LCD160CR.set_spi_win`, starting from the top-left corner.
@@ -325,35 +325,35 @@ Advanced commands
Configure a window region for scrolling:
- - `win` is the window id to configure. There are 0..7 standard windows for
+ - *win* is the window id to configure. There are 0..7 standard windows for
general purpose use. Window 8 is the text scroll window (the ticker).
- - `x`, `y`, `w`, `h` specify the location of the window in the display.
- - `vec` specifies the direction and speed of scroll: it is a 16-bit value
- of the form ``0bF.ddSSSSSSSSSSSS``. `dd` is 0, 1, 2, 3 for +x, +y, -x,
- -y scrolling. `F` sets the speed format, with 0 meaning that the window
- is shifted `S % 256` pixel every frame, and 1 meaning that the window
- is shifted 1 pixel every `S` frames.
- - `pat` is a 16-bit pattern mask for the background.
- - `fill` is the fill color.
- - `color` is the extra color, either of the text or pattern foreground.
+ - *x*, *y*, *w*, *h* specify the location of the window in the display.
+ - *vec* specifies the direction and speed of scroll: it is a 16-bit value
+ of the form ``0bF.ddSSSSSSSSSSSS``. *dd* is 0, 1, 2, 3 for +x, +y, -x,
+ -y scrolling. *F* sets the speed format, with 0 meaning that the window
+ is shifted *S % 256* pixel every frame, and 1 meaning that the window
+ is shifted 1 pixel every *S* frames.
+ - *pat* is a 16-bit pattern mask for the background.
+ - *fill* is the fill color.
+ - *color* is the extra color, either of the text or pattern foreground.
.. method:: LCD160CR.set_scroll_win_param(win, param, value)
Set a single parameter of a scrolling window region:
- - `win` is the window id, 0..8.
- - `param` is the parameter number to configure, 0..7, and corresponds
+ - *win* is the window id, 0..8.
+ - *param* is the parameter number to configure, 0..7, and corresponds
to the parameters in the `set_scroll_win` method.
- - `value` is the value to set.
+ - *value* is the value to set.
.. method:: LCD160CR.set_scroll_buf(s)
- Set the string for scrolling in window 8. The parameter `s` must be a string
+ Set the string for scrolling in window 8. The parameter *s* must be a string
with length 32 or less.
.. method:: LCD160CR.jpeg(buf)
- Display a JPEG. `buf` should contain the entire JPEG data. JPEG data should
+ Display a JPEG. *buf* should contain the entire JPEG data. JPEG data should
not include EXIF information. The following encodings are supported: Baseline
DCT, Huffman coding, 8 bits per sample, 3 color components, YCbCr4:2:2.
The origin of the JPEG is set by :meth:`LCD160CR.set_pos`.
@@ -380,15 +380,15 @@ Constants
---------
.. data:: lcd160cr.PORTRAIT
-.. data:: lcd160cr.LANDSCAPE
-.. data:: lcd160cr.PORTRAIT_UPSIDEDOWN
-.. data:: lcd160cr.LANDSCAPE_UPSIDEDOWN
+ lcd160cr.LANDSCAPE
+ lcd160cr.PORTRAIT_UPSIDEDOWN
+ lcd160cr.LANDSCAPE_UPSIDEDOWN
- orientation of the display, used by :meth:`LCD160CR.set_orient`
+ Orientations of the display, used by :meth:`LCD160CR.set_orient`.
.. data:: lcd160cr.STARTUP_DECO_NONE
-.. data:: lcd160cr.STARTUP_DECO_MLOGO
-.. data:: lcd160cr.STARTUP_DECO_INFO
+ lcd160cr.STARTUP_DECO_MLOGO
+ lcd160cr.STARTUP_DECO_INFO
- type of start-up decoration, can be or'd together, used by
- :meth:`LCD160CR.set_startup_deco`
+ Types of start-up decoration, can be OR'ed together, used by
+ :meth:`LCD160CR.set_startup_deco`.
diff --git a/docs/library/machine.I2C.rst b/docs/library/machine.I2C.rst
index a1b4178905..a69c58999f 100644
--- a/docs/library/machine.I2C.rst
+++ b/docs/library/machine.I2C.rst
@@ -37,16 +37,16 @@ Constructors
Construct and return a new I2C object using the following parameters:
- - `id` identifies the particular I2C peripheral. The default
+ - *id* identifies a particular I2C peripheral. The default
value of -1 selects a software implementation of I2C which can
work (in most cases) with arbitrary pins for SCL and SDA.
- If `id` is -1 then `scl` and `sda` must be specified. Other
- allowed values for `id` depend on the particular port/board,
- and specifying `scl` and `sda` may or may not be required or
+ If *id* is -1 then *scl* and *sda* must be specified. Other
+ allowed values for *id* depend on the particular port/board,
+ and specifying *scl* and *sda* may or may not be required or
allowed in this case.
- - `scl` should be a pin object specifying the pin to use for SCL.
- - `sda` should be a pin object specifying the pin to use for SDA.
- - `freq` should be an integer which sets the maximum frequency
+ - *scl* should be a pin object specifying the pin to use for SCL.
+ - *sda* should be a pin object specifying the pin to use for SDA.
+ - *freq* should be an integer which sets the maximum frequency
for SCL.
General Methods
@@ -56,9 +56,9 @@ General Methods
Initialise the I2C bus with the given arguments:
- - `scl` is a pin object for the SCL line
- - `sda` is a pin object for the SDA line
- - `freq` is the SCL clock rate
+ - *scl* is a pin object for the SCL line
+ - *sda* is a pin object for the SDA line
+ - *freq* is the SCL clock rate
.. method:: I2C.deinit()
@@ -93,9 +93,9 @@ control over the bus, otherwise the standard methods (see below) can be used.
.. method:: I2C.readinto(buf, nack=True)
- Reads bytes from the bus and stores them into `buf`. The number of bytes
- read is the length of `buf`. An ACK will be sent on the bus after
- receiving all but the last byte. After the last byte is received, if `nack`
+ Reads bytes from the bus and stores them into *buf*. The number of bytes
+ read is the length of *buf*. An ACK will be sent on the bus after
+ receiving all but the last byte. After the last byte is received, if *nack*
is true then a NACK will be sent, otherwise an ACK will be sent (and in this
case the slave assumes more bytes are going to be read in a later call).
@@ -103,7 +103,7 @@ control over the bus, otherwise the standard methods (see below) can be used.
.. method:: I2C.write(buf)
- Write the bytes from `buf` to the bus. Checks that an ACK is received
+ Write the bytes from *buf* to the bus. Checks that an ACK is received
after each byte and stops transmitting the remaining bytes if a NACK is
received. The function returns the number of ACKs that were received.
@@ -117,23 +117,23 @@ operations that target a given slave device.
.. method:: I2C.readfrom(addr, nbytes, stop=True)
- Read `nbytes` from the slave specified by `addr`.
- If `stop` is true then a STOP condition is generated at the end of the transfer.
+ Read *nbytes* from the slave specified by *addr*.
+ If *stop* is true then a STOP condition is generated at the end of the transfer.
Returns a `bytes` object with the data read.
.. method:: I2C.readfrom_into(addr, buf, stop=True)
- Read into `buf` from the slave specified by `addr`.
- The number of bytes read will be the length of `buf`.
- If `stop` is true then a STOP condition is generated at the end of the transfer.
+ Read into *buf* from the slave specified by *addr*.
+ The number of bytes read will be the length of *buf*.
+ If *stop* is true then a STOP condition is generated at the end of the transfer.
- The method returns `None`.
+ The method returns ``None``.
.. method:: I2C.writeto(addr, buf, stop=True)
- Write the bytes from `buf` to the slave specified by `addr`. If a
- NACK is received following the write of a byte from `buf` then the
- remaining bytes are not sent. If `stop` is true then a STOP condition is
+ Write the bytes from *buf* to the slave specified by *addr*. If a
+ NACK is received following the write of a byte from *buf* then the
+ remaining bytes are not sent. If *stop* is true then a STOP condition is
generated at the end of the transfer, even if a NACK is received.
The function returns the number of ACKs that were received.
@@ -147,26 +147,26 @@ methods are convenience functions to communicate with such devices.
.. method:: I2C.readfrom_mem(addr, memaddr, nbytes, \*, addrsize=8)
- Read `nbytes` from the slave specified by `addr` starting from the memory
- address specified by `memaddr`.
- The argument `addrsize` specifies the address size in bits.
+ Read *nbytes* from the slave specified by *addr* starting from the memory
+ address specified by *memaddr*.
+ The argument *addrsize* specifies the address size in bits.
Returns a `bytes` object with the data read.
.. method:: I2C.readfrom_mem_into(addr, memaddr, buf, \*, addrsize=8)
- Read into `buf` from the slave specified by `addr` starting from the
- memory address specified by `memaddr`. The number of bytes read is the
- length of `buf`.
- The argument `addrsize` specifies the address size in bits (on ESP8266
+ Read into *buf* from the slave specified by *addr* starting from the
+ memory address specified by *memaddr*. The number of bytes read is the
+ length of *buf*.
+ The argument *addrsize* specifies the address size in bits (on ESP8266
this argument is not recognised and the address size is always 8 bits).
- The method returns `None`.
+ The method returns ``None``.
.. method:: I2C.writeto_mem(addr, memaddr, buf, \*, addrsize=8)
- Write `buf` to the slave specified by `addr` starting from the
- memory address specified by `memaddr`.
- The argument `addrsize` specifies the address size in bits (on ESP8266
+ Write *buf* to the slave specified by *addr* starting from the
+ memory address specified by *memaddr*.
+ The argument *addrsize* specifies the address size in bits (on ESP8266
this argument is not recognised and the address size is always 8 bits).
- The method returns `None`.
+ The method returns ``None``.
diff --git a/docs/library/machine.RTC.rst b/docs/library/machine.RTC.rst
index 2a53b91469..95fa2b4ce6 100644
--- a/docs/library/machine.RTC.rst
+++ b/docs/library/machine.RTC.rst
@@ -38,7 +38,7 @@ Methods
Resets the RTC to the time of January 1, 2015 and starts running it again.
-.. method:: RTC.alarm(id, time, /*, repeat=False)
+.. method:: RTC.alarm(id, time, \*, repeat=False)
Set the RTC alarm. Time might be either a millisecond value to program the alarm to
current time + time_in_ms in the future, or a datetimetuple. If the time passed is in
diff --git a/docs/library/machine.UART.rst b/docs/library/machine.UART.rst
index 64ff28e1ab..983ef0a947 100644
--- a/docs/library/machine.UART.rst
+++ b/docs/library/machine.UART.rst
@@ -18,7 +18,7 @@ UART objects can be created and initialised using::
Supported parameters differ on a board:
-Pyboard: Bits can be 7, 8 or 9. Stop can be 1 or 2. With `parity=None`,
+Pyboard: Bits can be 7, 8 or 9. Stop can be 1 or 2. With *parity=None*,
only 8 and 9 bits are supported. With parity enabled, only 7 and 8 bits
are supported.
diff --git a/docs/library/machine.rst b/docs/library/machine.rst
index 7ea7f565e7..087f19cc6c 100644
--- a/docs/library/machine.rst
+++ b/docs/library/machine.rst
@@ -13,7 +13,7 @@ damage.
.. _machine_callbacks:
-A note of callbacks used by functions and class methods of ``machine`` module:
+A note of callbacks used by functions and class methods of :mod:`machine` module:
all these callbacks should be considered as executing in an interrupt context.
This is true for both physical devices with IDs >= 0 and "virtual" devices
with negative IDs like -1 (these "virtual" devices are still thin shims on
@@ -38,14 +38,14 @@ Interrupt related functions
Disable interrupt requests.
Returns the previous IRQ state which should be considered an opaque value.
- This return value should be passed to the ``enable_irq`` function to restore
- interrupts to their original state, before ``disable_irq`` was called.
+ This return value should be passed to the `enable_irq()` function to restore
+ interrupts to their original state, before `disable_irq()` was called.
.. function:: enable_irq(state)
Re-enable interrupt requests.
- The ``state`` parameter should be the value that was returned from the most
- recent call to the ``disable_irq`` function.
+ The *state* parameter should be the value that was returned from the most
+ recent call to the `disable_irq()` function.
Power related functions
-----------------------
@@ -71,8 +71,8 @@ Power related functions
Stops the CPU and all peripherals (including networking interfaces, if any). Execution
is resumed from the main script, just as with a reset. The reset cause can be checked
- to know that we are coming from ``machine.DEEPSLEEP``. For wake up to actually happen,
- wake sources should be configured first, like ``Pin`` change or ``RTC`` timeout.
+ to know that we are coming from `machine.DEEPSLEEP`. For wake up to actually happen,
+ wake sources should be configured first, like `Pin` change or `RTC` timeout.
.. only:: port_wipy
@@ -98,18 +98,18 @@ Miscellaneous functions
.. function:: time_pulse_us(pin, pulse_level, timeout_us=1000000)
- Time a pulse on the given `pin`, and return the duration of the pulse in
- microseconds. The `pulse_level` argument should be 0 to time a low pulse
+ Time a pulse on the given *pin*, and return the duration of the pulse in
+ microseconds. The *pulse_level* argument should be 0 to time a low pulse
or 1 to time a high pulse.
- If the current input value of the pin is different to `pulse_level`,
- the function first (*) waits until the pin input becomes equal to `pulse_level`,
- then (**) times the duration that the pin is equal to `pulse_level`.
- If the pin is already equal to `pulse_level` then timing starts straight away.
+ If the current input value of the pin is different to *pulse_level*,
+ the function first (*) waits until the pin input becomes equal to *pulse_level*,
+ then (**) times the duration that the pin is equal to *pulse_level*.
+ If the pin is already equal to *pulse_level* then timing starts straight away.
The function will return -2 if there was timeout waiting for condition marked
(*) above, and -1 if there was timeout during the main measurement, marked (**)
- above. The timeout is the same for both cases and given by `timeout_us` (which
+ above. The timeout is the same for both cases and given by *timeout_us* (which
is in microseconds).
.. _machine_constants:
diff --git a/docs/library/math.rst b/docs/library/math.rst
index 9d5cf7b4ba..a6f13d48c1 100644
--- a/docs/library/math.rst
+++ b/docs/library/math.rst
@@ -4,6 +4,8 @@
.. module:: math
:synopsis: mathematical functions
+|see_cpython_module| :mod:`python:math`.
+
The ``math`` module provides some basic mathematical functions for
working with floating-point numbers.
diff --git a/docs/library/micropython.rst b/docs/library/micropython.rst
index 7f40028565..4ff0b0c159 100644
--- a/docs/library/micropython.rst
+++ b/docs/library/micropython.rst
@@ -23,30 +23,30 @@ Functions
variable, and does not take up any memory during execution.
This `const` function is recognised directly by the MicroPython parser and is
- provided as part of the `micropython` module mainly so that scripts can be
+ provided as part of the :mod:`micropython` module mainly so that scripts can be
written which run under both CPython and MicroPython, by following the above
pattern.
.. function:: opt_level([level])
- If `level` is given then this function sets the optimisation level for subsequent
- compilation of scripts, and returns `None`. Otherwise it returns the current
+ If *level* is given then this function sets the optimisation level for subsequent
+ compilation of scripts, and returns ``None``. Otherwise it returns the current
optimisation level.
.. function:: alloc_emergency_exception_buf(size)
- Allocate ``size`` bytes of RAM for the emergency exception buffer (a good
+ Allocate *size* bytes of RAM for the emergency exception buffer (a good
size is around 100 bytes). The buffer is used to create exceptions in cases
when normal RAM allocation would fail (eg within an interrupt handler) and
therefore give useful traceback information in these situations.
A good way to use this function is to put it at the start of your main script
- (eg boot.py or main.py) and then the emergency exception buffer will be active
+ (eg ``boot.py`` or ``main.py``) and then the emergency exception buffer will be active
for all the code following it.
.. function:: mem_info([verbose])
- Print information about currently used memory. If the ``verbose`` argument
+ Print information about currently used memory. If the *verbose`* argument
is given then extra information is printed.
The information that is printed is implementation dependent, but currently
@@ -55,7 +55,7 @@ Functions
.. function:: qstr_info([verbose])
- Print information about currently interned strings. If the ``verbose``
+ Print information about currently interned strings. If the *verbose*
argument is given then extra information is printed.
The information that is printed is implementation dependent, but currently
@@ -89,10 +89,10 @@ Functions
incoming stream of characters that is usually used for the REPL, in case
that stream is used for other purposes.
-.. function:: schedule(fun, arg)
+.. function:: schedule(func, arg)
- Schedule the function `fun` to be executed "very soon". The function
- is passed the value `arg` as its single argument. "very soon" means that
+ Schedule the function *func* to be executed "very soon". The function
+ is passed the value *arg* as its single argument. "Very soon" means that
the MicroPython runtime will do its best to execute the function at the
earliest possible time, given that it is also trying to be efficient, and
that the following conditions hold:
diff --git a/docs/library/network.rst b/docs/library/network.rst
index 27fa0dcb2f..de93c0e01d 100644
--- a/docs/library/network.rst
+++ b/docs/library/network.rst
@@ -72,7 +72,7 @@ parameter should be `id`.
connection parameters. For various medium types, there are different
sets of predefined/recommended parameters, among them:
- * WiFi: `bssid` keyword to connect by BSSID (MAC address) instead
+ * WiFi: *bssid* keyword to connect by BSSID (MAC address) instead
of access point name
.. method:: disconnect()
@@ -118,7 +118,7 @@ parameter should be `id`.
Get or set general network interface parameters. These methods allow to work
with additional parameters beyond standard IP configuration (as dealt with by
- ``ifconfig()``). These include network-specific and hardware-specific
+ `ifconfig()`). These include network-specific and hardware-specific
parameters and status values. For setting parameters, the keyword argument
syntax should be used, and multiple parameters can be set at once. For
querying, a parameter name should be quoted as a string, and only one
@@ -170,11 +170,11 @@ parameter should be `id`.
Arguments are:
- - ``spi`` is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the CC3000 is
+ - *spi* is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the CC3000 is
connected to (the MOSI, MISO and CLK pins).
- - ``pin_cs`` is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 CS pin.
- - ``pin_en`` is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 VBEN pin.
- - ``pin_irq`` is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 IRQ pin.
+ - *pin_cs* is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 CS pin.
+ - *pin_en* is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 VBEN pin.
+ - *pin_irq* is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 IRQ pin.
All of these objects will be initialised by the driver, so there is no need to
initialise them yourself. For example, you can use::
@@ -256,10 +256,10 @@ parameter should be `id`.
Arguments are:
- - ``spi`` is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the WIZnet5x00 is
+ - *spi* is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the WIZnet5x00 is
connected to (the MOSI, MISO and SCLK pins).
- - ``pin_cs`` is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nSS pin.
- - ``pin_rst`` is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nRESET pin.
+ - *pin_cs* is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nSS pin.
+ - *pin_rst* is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nRESET pin.
All of these objects will be initialised by the driver, so there is no need to
initialise them yourself. For example, you can use::
@@ -294,7 +294,7 @@ parameter should be `id`.
Get or set the PHY mode.
- If the ``mode`` parameter is provided, sets the mode to its value. If
+ If the *mode* parameter is provided, sets the mode to its value. If
the function is called without parameters, returns the current mode.
The possible modes are defined as constants:
@@ -322,7 +322,7 @@ parameter should be `id`.
``network.STA_IF`` (station aka client, connects to upstream WiFi access
points) and ``network.AP_IF`` (access point, allows other WiFi clients to
connect). Availability of the methods below depends on interface type.
- For example, only STA interface may ``connect()`` to an access point.
+ For example, only STA interface may `connect()` to an access point.
Methods
-------
@@ -350,8 +350,8 @@ parameter should be `id`.
(ssid, bssid, channel, RSSI, authmode, hidden)
- `bssid` is hardware address of an access point, in binary form, returned as
- bytes object. You can use ``ubinascii.hexlify()`` to convert it to ASCII form.
+ *bssid* is hardware address of an access point, in binary form, returned as
+ bytes object. You can use `ubinascii.hexlify()` to convert it to ASCII form.
There are five values for authmode:
@@ -399,7 +399,7 @@ parameter should be `id`.
Get or set general network interface parameters. These methods allow to work
with additional parameters beyond standard IP configuration (as dealt with by
- ``wlan.ifconfig()``). These include network-specific and hardware-specific
+ `wlan.ifconfig()`). These include network-specific and hardware-specific
parameters. For setting parameters, keyword argument syntax should be used,
multiple parameters can be set at once. For querying, parameters name should
be quoted as a string, and only one parameter can be queries at time::
@@ -450,7 +450,7 @@ parameter should be `id`.
.. class:: WLAN(id=0, ...)
- Create a WLAN object, and optionally configure it. See ``init`` for params of configuration.
+ Create a WLAN object, and optionally configure it. See `init()` for params of configuration.
.. note::
@@ -469,14 +469,14 @@ parameter should be `id`.
Arguments are:
- - ``mode`` can be either ``WLAN.STA`` or ``WLAN.AP``.
- - ``ssid`` is a string with the ssid name. Only needed when mode is ``WLAN.AP``.
- - ``auth`` is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``,
+ - *mode* can be either ``WLAN.STA`` or ``WLAN.AP``.
+ - *ssid* is a string with the ssid name. Only needed when mode is ``WLAN.AP``.
+ - *auth* is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``,
``WLAN.WPA`` or ``WLAN.WPA2``. The key is a string with the network password.
If ``sec`` is ``WLAN.WEP`` the key must be a string representing hexadecimal
values (e.g. 'ABC1DE45BF'). Only needed when mode is ``WLAN.AP``.
- - ``channel`` a number in the range 1-11. Only needed when mode is ``WLAN.AP``.
- - ``antenna`` selects between the internal and the external antenna. Can be either
+ - *channel* a number in the range 1-11. Only needed when mode is ``WLAN.AP``.
+ - *antenna* selects between the internal and the external antenna. Can be either
``WLAN.INT_ANT`` or ``WLAN.EXT_ANT``.
For example, you can do::
@@ -494,13 +494,13 @@ parameter should be `id`.
Connect to a WiFi access point using the given SSID, and other security
parameters.
- - ``auth`` is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``,
+ - *auth* is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``,
``WLAN.WPA`` or ``WLAN.WPA2``. The key is a string with the network password.
If ``sec`` is ``WLAN.WEP`` the key must be a string representing hexadecimal
values (e.g. 'ABC1DE45BF').
- - ``bssid`` is the MAC address of the AP to connect to. Useful when there are several
+ - *bssid* is the MAC address of the AP to connect to. Useful when there are several
APs with the same ssid.
- - ``timeout`` is the maximum time in milliseconds to wait for the connection to succeed.
+ - *timeout* is the maximum time in milliseconds to wait for the connection to succeed.
.. method:: wlan.scan()
@@ -518,7 +518,7 @@ parameter should be `id`.
.. method:: wlan.ifconfig(if_id=0, config=['dhcp' or configtuple])
- With no parameters given returns a 4-tuple of ``(ip, subnet_mask, gateway, DNS_server)``.
+ With no parameters given returns a 4-tuple of *(ip, subnet_mask, gateway, DNS_server)*.
if ``'dhcp'`` is passed as a parameter then the DHCP client is enabled and the IP params
are negotiated with the AP.
@@ -556,8 +556,8 @@ parameter should be `id`.
Create a callback to be triggered when a WLAN event occurs during ``machine.SLEEP``
mode. Events are triggered by socket activity or by WLAN connection/disconnection.
- - ``handler`` is the function that gets called when the IRQ is triggered.
- - ``wake`` must be ``machine.SLEEP``.
+ - *handler* is the function that gets called when the IRQ is triggered.
+ - *wake* must be ``machine.SLEEP``.
Returns an IRQ object.
diff --git a/docs/library/pyb.Switch.rst b/docs/library/pyb.Switch.rst
index bc62b6eee9..0d5dc63b74 100644
--- a/docs/library/pyb.Switch.rst
+++ b/docs/library/pyb.Switch.rst
@@ -8,7 +8,8 @@ A Switch object is used to control a push-button switch.
Usage::
sw = pyb.Switch() # create a switch object
- sw() # get state (True if pressed, False otherwise)
+ sw.value() # get state (True if pressed, False otherwise)
+ sw() # shorthand notation to get the switch state
sw.callback(f) # register a callback to be called when the
# switch is pressed down
sw.callback(None) # remove the callback
@@ -34,6 +35,10 @@ Methods
Call switch object directly to get its state: ``True`` if pressed down,
``False`` otherwise.
+.. method:: Switch.value()
+
+ Get the switch state. Returns `True` if pressed down, otherwise `False`.
+
.. method:: Switch.callback(fun)
Register the given function to be called when the switch is pressed down.
diff --git a/docs/library/pyb.rst b/docs/library/pyb.rst
index 9c4933808a..7991601457 100644
--- a/docs/library/pyb.rst
+++ b/docs/library/pyb.rst
@@ -21,7 +21,7 @@ Time related functions
Returns the number of milliseconds since the board was last reset.
- The result is always a micropython smallint (31-bit signed number), so
+ The result is always a MicroPython smallint (31-bit signed number), so
after 2^30 milliseconds (about 12.4 days) this will start to return
negative numbers.
@@ -33,7 +33,7 @@ Time related functions
Returns the number of microseconds since the board was last reset.
- The result is always a micropython smallint (31-bit signed number), so
+ The result is always a MicroPython smallint (31-bit signed number), so
after 2^30 microseconds (about 17.8 minutes) this will start to return
negative numbers.
@@ -85,10 +85,10 @@ Reset related functions
Enable or disable hard-fault debugging. A hard-fault is when there is a fatal
error in the underlying system, like an invalid memory access.
- If the `value` argument is `False` then the board will automatically reset if
+ If the *value* argument is ``False`` then the board will automatically reset if
there is a hard fault.
- If `value` is `True` then, when the board has a hard fault, it will print the
+ If *value* is ``True`` then, when the board has a hard fault, it will print the
registers and the stack trace, and then cycle the LEDs indefinitely.
The default value is disabled, i.e. to automatically reset.
diff --git a/docs/library/sys.rst b/docs/library/sys.rst
index 1d7579754f..d49577306e 100644
--- a/docs/library/sys.rst
+++ b/docs/library/sys.rst
@@ -4,19 +4,21 @@
.. module:: sys
:synopsis: system specific functions
+|see_cpython_module| :mod:`python:sys`.
+
Functions
---------
.. function:: exit(retval=0)
Terminate current program with a given exit code. Underlyingly, this
- function raise as ``SystemExit`` exception. If an argument is given, its
- value given as an argument to ``SystemExit``.
+ function raise as `SystemExit` exception. If an argument is given, its
+ value given as an argument to `SystemExit`.
.. function:: print_exception(exc, file=sys.stdout)
- Print exception with a traceback to a file-like object `file` (or
- ``sys.stdout`` by default).
+ Print exception with a traceback to a file-like object *file* (or
+ `sys.stdout` by default).
.. admonition:: Difference to CPython
:class: attention
@@ -24,9 +26,9 @@ Functions
This is simplified version of a function which appears in the
``traceback`` module in CPython. Unlike ``traceback.print_exception()``,
this function takes just exception value instead of exception type,
- exception value, and traceback object; `file` argument should be
+ exception value, and traceback object; *file* argument should be
positional; further arguments are not supported. CPython-compatible
- ``traceback`` module can be found in micropython-lib.
+ ``traceback`` module can be found in `micropython-lib`.
Constants
---------
@@ -37,15 +39,15 @@ Constants
.. data:: byteorder
- The byte order of the system ("little" or "big").
+ The byte order of the system (``"little"`` or ``"big"``).
.. data:: implementation
Object with information about the current Python implementation. For
MicroPython, it has following attributes:
- * `name` - string "micropython"
- * `version` - tuple (major, minor, micro), e.g. (1, 7, 0)
+ * *name* - string "micropython"
+ * *version* - tuple (major, minor, micro), e.g. (1, 7, 0)
This object is the recommended way to distinguish MicroPython from other
Python implementations (note that it still may not exist in the very
@@ -95,10 +97,10 @@ Constants
The platform that MicroPython is running on. For OS/RTOS ports, this is
usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it
- is an identifier of a board, e.g. "pyboard" for the original MicroPython
+ is an identifier of a board, e.g. ``"pyboard"`` for the original MicroPython
reference board. It thus can be used to distinguish one board from another.
If you need to check whether your program runs on MicroPython (vs other
- Python implementation), use ``sys.implementation`` instead.
+ Python implementation), use `sys.implementation` instead.
.. data:: stderr
diff --git a/docs/library/ubinascii.rst b/docs/library/ubinascii.rst
index 4931f90482..192d34514b 100644
--- a/docs/library/ubinascii.rst
+++ b/docs/library/ubinascii.rst
@@ -4,6 +4,8 @@
.. module:: ubinascii
:synopsis: binary/ASCII conversions
+|see_cpython_module| :mod:`python:binascii`.
+
This module implements conversions between binary data and various
encodings of it in ASCII form (in both directions).
@@ -17,7 +19,7 @@ Functions
.. admonition:: Difference to CPython
:class: attention
- If additional argument, `sep` is supplied, it is used as a separator
+ If additional argument, *sep* is supplied, it is used as a separator
between hexadecimal values.
.. function:: unhexlify(data)
@@ -27,8 +29,12 @@ Functions
.. function:: a2b_base64(data)
- Convert Base64-encoded data to binary representation. Returns bytes string.
+ Decode base64-encoded data, ignoring invalid characters in the input.
+ Conforms to `RFC 2045 s.6.8 <https://tools.ietf.org/html/rfc2045#section-6.8>`_.
+ Returns a bytes object.
.. function:: b2a_base64(data)
- Encode binary data in Base64 format. Returns string.
+ Encode binary data in base64 format, as in `RFC 3548
+ <https://tools.ietf.org/html/rfc3548.html>`_. Returns the encoded data
+ followed by a newline character, as a bytes object.
diff --git a/docs/library/ucollections.rst b/docs/library/ucollections.rst
index 4e9de9ac67..96de67acc4 100644
--- a/docs/library/ucollections.rst
+++ b/docs/library/ucollections.rst
@@ -4,6 +4,8 @@
.. module:: ucollections
:synopsis: collection and container types
+|see_cpython_module| :mod:`python:collections`.
+
This module implements advanced collection and container types to
hold/accumulate various objects.
diff --git a/docs/library/uerrno.rst b/docs/library/uerrno.rst
new file mode 100644
index 0000000000..0cdcc84487
--- /dev/null
+++ b/docs/library/uerrno.rst
@@ -0,0 +1,34 @@
+:mod:`uerrno` -- system error codes
+===================================
+
+.. module:: uerrno
+ :synopsis: system error codes
+
+|see_cpython_module| :mod:`python:errno`.
+
+This module provides access to symbolic error codes for `OSError` exception.
+A particular inventory of codes depends on `MicroPython port`.
+
+Constants
+---------
+
+.. data:: EEXIST, EAGAIN, etc.
+
+ Error codes, based on ANSI C/POSIX standard. All error codes start with
+ "E". As mentioned above, inventory of the codes depends on
+ `MicroPython port`. Errors are usually accessible as ``exc.args[0]``
+ where `exc` is an instance of `OSError`. Usage example::
+
+ try:
+ uos.mkdir("my_dir")
+ except OSError as exc:
+ if exc.args[0] == uerrno.EEXIST:
+ print("Directory already exists")
+
+.. data:: errorcode
+
+ Dictionary mapping numeric error codes to strings with symbolic error
+ code (see above)::
+
+ >>> print(uerrno.errorcode[uerrno.EEXIST])
+ EEXIST
diff --git a/docs/library/uhashlib.rst b/docs/library/uhashlib.rst
index 6b9a764ba8..50ed658cc1 100644
--- a/docs/library/uhashlib.rst
+++ b/docs/library/uhashlib.rst
@@ -4,6 +4,8 @@
.. module:: uhashlib
:synopsis: hashing algorithms
+|see_cpython_module| :mod:`python:hashlib`.
+
This module implements binary data hashing algorithms. The exact inventory
of available algorithms depends on a board. Among the algorithms which may
be implemented:
diff --git a/docs/library/uheapq.rst b/docs/library/uheapq.rst
index c17dac0675..f822f1e7f3 100644
--- a/docs/library/uheapq.rst
+++ b/docs/library/uheapq.rst
@@ -4,6 +4,8 @@
.. module:: uheapq
:synopsis: heap queue algorithm
+|see_cpython_module| :mod:`python:heapq`.
+
This module implements the heap queue algorithm.
A heap queue is simply a list that has its elements stored in a certain way.
diff --git a/docs/library/uio.rst b/docs/library/uio.rst
index 1239c6394e..7042a9e376 100644
--- a/docs/library/uio.rst
+++ b/docs/library/uio.rst
@@ -4,6 +4,8 @@
.. module:: uio
:synopsis: input/output streams
+|see_cpython_module| :mod:`python:io`.
+
This module contains additional types of stream (file-like) objects
and helper functions.
diff --git a/docs/library/ujson.rst b/docs/library/ujson.rst
index 724bc90ee1..0932d0ab55 100644
--- a/docs/library/ujson.rst
+++ b/docs/library/ujson.rst
@@ -4,6 +4,8 @@
.. module:: ujson
:synopsis: JSON encoding and decoding
+|see_cpython_module| :mod:`python:json`.
+
This modules allows to convert between Python objects and the JSON
data format.
diff --git a/docs/library/uos.rst b/docs/library/uos.rst
index 3d0aa46c70..7c52c1eead 100644
--- a/docs/library/uos.rst
+++ b/docs/library/uos.rst
@@ -4,6 +4,8 @@
.. module:: uos
:synopsis: basic "operating system" services
+|see_cpython_module| :mod:`python:os`.
+
The ``uos`` module contains functions for filesystem access and ``urandom``
function.
@@ -22,15 +24,15 @@ Functions
This function returns an iterator which then yields 3-tuples corresponding to
the entries in the directory that it is listing. With no argument it lists the
- current directory, otherwise it lists the directory given by `dir`.
+ current directory, otherwise it lists the directory given by *dir*.
- The 3-tuples have the form `(name, type, inode)`:
+ The 3-tuples have the form *(name, type, inode)*:
- - `name` is a string (or bytes if `dir` is a bytes object) and is the name of
+ - *name* is a string (or bytes if *dir* is a bytes object) and is the name of
the entry;
- - `type` is an integer that specifies the type of the entry, with 0x4000 for
+ - *type* is an integer that specifies the type of the entry, with 0x4000 for
directories and 0x8000 for regular files;
- - `inode` is an integer corresponding to the inode of the file, and may be 0
+ - *inode* is an integer corresponding to the inode of the file, and may be 0
for filesystems that don't have such a notion.
.. function:: listdir([dir])
@@ -90,5 +92,5 @@ Functions
.. function:: dupterm(stream_object)
Duplicate or switch MicroPython terminal (the REPL) on the passed stream-like
- object. The given object must implement the `.readinto()` and `.write()`
+ object. The given object must implement the ``readinto()`` and ``write()``
methods. If ``None`` is passed, previously set redirection is cancelled.
diff --git a/docs/library/ure.rst b/docs/library/ure.rst
index ee360bcc47..67f4f54a1d 100644
--- a/docs/library/ure.rst
+++ b/docs/library/ure.rst
@@ -1,9 +1,11 @@
-:mod:`ure` -- regular expressions
-=================================
+:mod:`ure` -- simple regular expressions
+========================================
.. module:: ure
:synopsis: regular expressions
+|see_cpython_module| :mod:`python:re`.
+
This module implements regular expression operations. Regular expression
syntax supported is a subset of CPython ``re`` module (and actually is
a subset of POSIX extended regular expressions).
@@ -32,6 +34,10 @@ Supported operators are:
``'+?'``
+``'()'``
+ Grouping. Each group is capturing (a substring it captures can be accessed
+ with `match.group()` method).
+
Counted repetitions (``{m,n}``), more advanced assertions, named groups,
etc. are not supported.
@@ -39,18 +45,18 @@ etc. are not supported.
Functions
---------
-.. function:: compile(regex)
+.. function:: compile(regex_str)
- Compile regular expression, return ``regex`` object.
+ Compile regular expression, return `regex <regex>` object.
-.. function:: match(regex, string)
+.. function:: match(regex_str, string)
- Match ``regex`` against ``string``. Match always happens from starting
- position in a string.
+ Compile *regex_str* and match against *string*. Match always happens
+ from starting position in a string.
-.. function:: search(regex, string)
+.. function:: search(regex_str, string)
- Search ``regex`` in a ``string``. Unlike ``match``, this will search
+ Compile *regex_str* and search it in a *string*. Unlike `match`, this will search
string for first position which matches regex (which still may be
0 if regex is anchored).
@@ -59,24 +65,33 @@ Functions
Flag value, display debug information about compiled expression.
+.. _regex:
+
Regex objects
-------------
Compiled regular expression. Instances of this class are created using
-``ure.compile()``.
+`ure.compile()`.
.. method:: regex.match(string)
+ regex.search(string)
-.. method:: regex.search(string)
+ Similar to the module-level functions :meth:`match` and :meth:`search`.
+ Using methods is (much) more efficient if the same regex is applied to
+ multiple strings.
.. method:: regex.split(string, max_split=-1)
+ Split a *string* using regex. If *max_split* is given, it specifies
+ maximum number of splits to perform. Returns list of strings (there
+ may be up to *max_split+1* elements if it's specified).
Match objects
-------------
-Match objects as returned by ``match()`` and ``search()`` methods.
+Match objects as returned by `match()` and `search()` methods.
.. method:: match.group([index])
- Only numeric groups are supported.
+ Return matching (sub)string. *index* is 0 for entire match,
+ 1 and above for each capturing group. Only numeric groups are supported.
diff --git a/docs/library/select.rst b/docs/library/uselect.rst
index 8dcd4080f1..e330207dbd 100644
--- a/docs/library/select.rst
+++ b/docs/library/uselect.rst
@@ -1,18 +1,13 @@
-:mod:`select` -- wait for events on a set of streams
+:mod:`uselect` -- wait for events on a set of streams
========================================================================
-.. module:: select
+.. module:: uselect
:synopsis: wait for events on a set of streams
-This module provides functions to wait for events on streams (select streams
-which are ready for operations).
+|see_cpython_module| :mod:`python:select`.
-Pyboard specifics
------------------
-
-Polling is an efficient way of waiting for read/write activity on multiple
-objects. Current objects that support polling are: :class:`pyb.UART`,
-:class:`pyb.USB_VCP`.
+This module provides functions to efficiently wait for events on multiple
+streams (select streams which are ready for operations).
Functions
---------
@@ -25,8 +20,8 @@ Functions
Wait for activity on a set of objects.
- This function is provided for compatibility and is not efficient. Usage
- of :class:`Poll` is recommended instead.
+ This function is provided by some MicroPython ports for compatibility
+ and is not efficient. Usage of :class:`Poll` is recommended instead.
.. _class: Poll
@@ -38,30 +33,46 @@ Methods
.. method:: poll.register(obj[, eventmask])
- Register ``obj`` for polling. ``eventmask`` is logical OR of:
+ Register *obj* for polling. *eventmask* is logical OR of:
* ``select.POLLIN`` - data available for reading
* ``select.POLLOUT`` - more data can be written
* ``select.POLLERR`` - error occurred
* ``select.POLLHUP`` - end of stream/connection termination detected
- ``eventmask`` defaults to ``select.POLLIN | select.POLLOUT``.
+ *eventmask* defaults to ``select.POLLIN | select.POLLOUT``.
.. method:: poll.unregister(obj)
- Unregister ``obj`` from polling.
+ Unregister *obj* from polling.
.. method:: poll.modify(obj, eventmask)
- Modify the ``eventmask`` for ``obj``.
+ Modify the *eventmask* for *obj*.
.. method:: poll.poll([timeout])
Wait for at least one of the registered objects to become ready. Returns
list of (``obj``, ``event``, ...) tuples, ``event`` element specifies
- which events happened with a stream and is a combination of `select.POLL*`
+ which events happened with a stream and is a combination of ``select.POLL*``
constants described above. There may be other elements in tuple, depending
on a platform and version, so don't assume that its size is 2. In case of
timeout, an empty list is returned.
Timeout is in milliseconds.
+
+ .. admonition:: Difference to CPython
+ :class: attention
+
+ Tuples returned may contain more than 2 elements as described above.
+
+.. method:: poll.ipoll([timeout])
+
+ Like :meth:`poll.poll`, but instead returns an iterator which yields
+ callee-owned tuples. This function provides efficient, allocation-free
+ way to poll on streams.
+
+ .. admonition:: Difference to CPython
+ :class: attention
+
+ This function is a MicroPython extension.
diff --git a/docs/library/usocket.rst b/docs/library/usocket.rst
index 71deaebc41..65e24e2662 100644
--- a/docs/library/usocket.rst
+++ b/docs/library/usocket.rst
@@ -5,43 +5,72 @@
.. module:: usocket
:synopsis: socket module
-This module provides access to the BSD socket interface.
-
-See the corresponding `CPython module <https://docs.python.org/3/library/socket.html>`_
-for comparison.
-
-.. admonition:: Difference to CPython
- :class: attention
+|see_cpython_module| :mod:`python:socket`.
- CPython used to have a ``socket.error`` exception which is now deprecated,
- and is an alias of OSError. In MicroPython, use OSError directly.
+This module provides access to the BSD socket interface.
.. admonition:: Difference to CPython
:class: attention
For efficiency and consistency, socket objects in MicroPython implement a stream
(file-like) interface directly. In CPython, you need to convert a socket to
- a file-like object using ``makefile()`` method. This method is still supported
+ a file-like object using `makefile()` method. This method is still supported
by MicroPython (but is a no-op), so where compatibility with CPython matters,
be sure to use it.
Socket address format(s)
------------------------
-The functions below which expect a network address, accept it in the format of
-`(ipv4_address, port)`, where `ipv4_address` is a string with dot-notation numeric
-IPv4 address, e.g. ``"8.8.8.8"``, and port is integer port number in the range
-1-65535. Note the domain names are not accepted as `ipv4_address`, they should be
-resolved first using ``socket.getaddrinfo()``.
+The native socket address format of the ``usocket`` module is an opaque data type
+returned by `getaddrinfo` function, which must be used to resolve textual address
+(including numeric addresses)::
+
+ sockaddr = usocket.getaddrinfo('www.micropython.org', 80)[0][-1]
+ # You must use getaddrinfo() even for numeric addresses
+ sockaddr = usocket.getaddrinfo('127.0.0.1', 80)[0][-1]
+ # Now you can use that address
+ sock.connect(addr)
+
+Using `getaddrinfo` is the most efficient (both in terms of memory and processing
+power) and portable way to work with addresses.
+
+However, ``socket`` module (note the difference with native MicroPython
+``usocket`` module described here) provides CPython-compatible way to specify
+addresses using tuples, as described below. Note that depending on a
+`MicroPython port`, ``socket`` module can be builtin or need to be
+installed from `micropython-lib` (as in the case of `MicroPython Unix port`),
+and some ports still accept only numeric addresses in the tuple format,
+and require to use `getaddrinfo` function to resolve domain names.
+
+Summing up:
+
+* Always use `getaddrinfo` when writing portable applications.
+* Tuple addresses described below can be used as a shortcut for
+ quick hacks and interactive use, if your port supports them.
+
+Tuple address format for ``socket`` module:
+
+* IPv4: *(ipv4_address, port)*, where *ipv4_address* is a string with
+ dot-notation numeric IPv4 address, e.g. ``"8.8.8.8"``, and *port* is and
+ integer port number in the range 1-65535. Note the domain names are not
+ accepted as *ipv4_address*, they should be resolved first using
+ `usocket.getaddrinfo()`.
+* IPv6: *(ipv6_address, port, flowinfo, scopeid)*, where *ipv6_address*
+ is a string with colon-notation numeric IPv6 address, e.g. ``"2001:db8::1"``,
+ and *port* is an integer port number in the range 1-65535. *flowinfo*
+ must be 0. *scopeid* is the interface scope identifier for link-local
+ addresses. Note the domain names are not accepted as *ipv6_address*,
+ they should be resolved first using `usocket.getaddrinfo()`. Availability
+ of IPv6 support depends on a `MicroPython port`.
Functions
---------
-.. function:: socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
+.. function:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP)
Create a new socket using the given address family, socket type and protocol number.
-.. function:: socket.getaddrinfo(host, port)
+.. function:: getaddrinfo(host, port)
Translate the host/port argument into a sequence of 5-tuples that contain all the
necessary arguments for creating a socket connected to that service. The list of
@@ -57,11 +86,11 @@ Functions
.. admonition:: Difference to CPython
:class: attention
- CPython raises a ``socket.gaierror`` exception (OSError subclass) in case
+ CPython raises a ``socket.gaierror`` exception (`OSError` subclass) in case
of error in this function. MicroPython doesn't have ``socket.gaierror``
- and raises OSError directly. Note that error numbers of ``getaddrinfo()``
+ and raises OSError directly. Note that error numbers of `getaddrinfo()`
form a separate namespace and may not match error numbers from
- ``uerrno`` module. To distinguish ``getaddrinfo()`` errors, they are
+ `uerrno` module. To distinguish `getaddrinfo()` errors, they are
represented by negative numbers, whereas standard system errors are
positive numbers (error numbers are accessible using ``e.args[0]`` property
from an exception object). The use of negative values is a provisional
@@ -70,32 +99,34 @@ Functions
Constants
---------
-.. data:: socket.AF_INET
- socket.AF_INET6
+.. data:: AF_INET
+ AF_INET6
Address family types. Availability depends on a particular board.
-.. data:: socket.SOCK_STREAM
- socket.SOCK_DGRAM
+.. data:: SOCK_STREAM
+ SOCK_DGRAM
Socket types.
-.. data:: socket.IPPROTO_UDP
- socket.IPPROTO_TCP
+.. data:: IPPROTO_UDP
+ IPPROTO_TCP
IP protocol numbers.
-.. data:: socket.SOL_*
+.. data:: usocket.SOL_*
- Socket option levels (an argument to ``setsockopt()``). The exact inventory depends on a board.
+ Socket option levels (an argument to `setsockopt()`). The exact
+ inventory depends on a MicroPython port.
-.. data:: socket.SO_*
+.. data:: usocket.SO_*
- Socket options (an argument to ``setsockopt()``). The exact inventory depends on a board.
+ Socket options (an argument to `setsockopt()`). The exact
+ inventory depends on a MicroPython port.
Constants specific to WiPy:
-.. data:: socket.IPPROTO_SEC
+.. data:: IPPROTO_SEC
Special protocol value to create SSL-compatible socket.
@@ -105,21 +136,22 @@ class socket
Methods
-------
-.. method:: socket.close
+.. method:: socket.close()
- Mark the socket closed. Once that happens, all future operations on the socket
- object will fail. The remote end will receive no more data (after queued data is flushed).
+ Mark the socket closed and release all resources. Once that happens, all future operations
+ on the socket object will fail. The remote end will receive EOF indication if
+ supported by protocol.
Sockets are automatically closed when they are garbage-collected, but it is recommended
- to close() them explicitly, or to use a with statement around them.
+ to `close()` them explicitly as soon you finished working with them.
.. method:: socket.bind(address)
- Bind the socket to address. The socket must not already be bound.
+ Bind the socket to *address*. The socket must not already be bound.
.. method:: socket.listen([backlog])
- Enable a server to accept connections. If backlog is specified, it must be at least 0
+ Enable a server to accept connections. If *backlog* is specified, it must be at least 0
(if it's lower, it will be set to 0); and specifies the number of unaccepted connections
that the system will allow before refusing new connections. If not specified, a default
reasonable value is chosen.
@@ -133,7 +165,7 @@ Methods
.. method:: socket.connect(address)
- Connect to a remote socket at address.
+ Connect to a remote socket at *address*.
.. method:: socket.send(bytes)
@@ -144,11 +176,11 @@ Methods
.. method:: socket.sendall(bytes)
Send all data to the socket. The socket must be connected to a remote socket.
- Unlike ``send()``, this method will try to send all of data, by sending data
+ Unlike `send()`, this method will try to send all of data, by sending data
chunk by chunk consecutively.
The behavior of this method on non-blocking sockets is undefined. Due to this,
- on MicroPython, it's recommended to use ``write()`` method instead, which
+ on MicroPython, it's recommended to use `write()` method instead, which
has the same "no short writes" policy for blocking sockets, and will return
number of bytes sent on non-blocking sockets.
@@ -160,25 +192,25 @@ Methods
.. method:: socket.sendto(bytes, address)
Send data to the socket. The socket should not be connected to a remote socket, since the
- destination socket is specified by `address`.
+ destination socket is specified by *address*.
.. method:: socket.recvfrom(bufsize)
- Receive data from the socket. The return value is a pair (bytes, address) where bytes is a
- bytes object representing the data received and address is the address of the socket sending
+ Receive data from the socket. The return value is a pair *(bytes, address)* where *bytes* is a
+ bytes object representing the data received and *address* is the address of the socket sending
the data.
.. method:: socket.setsockopt(level, optname, value)
Set the value of the given socket option. The needed symbolic constants are defined in the
- socket module (SO_* etc.). The value can be an integer or a bytes-like object representing
+ socket module (SO_* etc.). The *value* can be an integer or a bytes-like object representing
a buffer.
.. method:: socket.settimeout(value)
Set a timeout on blocking socket operations. The value argument can be a nonnegative floating
point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations
- will raise an ``OSError`` exception if the timeout period value has elapsed before the operation has
+ will raise an `OSError` exception if the timeout period value has elapsed before the operation has
completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket
is put in blocking mode.
@@ -186,7 +218,7 @@ Methods
:class: attention
CPython raises a ``socket.timeout`` exception in case of timeout,
- which is an ``OSError`` subclass. MicroPython raises an OSError directly
+ which is an `OSError` subclass. MicroPython raises an OSError directly
instead. If you use ``except OSError:`` to catch the exception,
your code will work both in MicroPython and CPython.
@@ -195,7 +227,7 @@ Methods
Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking,
else to blocking mode.
- This method is a shorthand for certain ``settimeout()`` calls:
+ This method is a shorthand for certain `settimeout()` calls:
* ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)``
* ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0)``
@@ -204,12 +236,12 @@ Methods
Return a file object associated with the socket. The exact returned type depends on the arguments
given to makefile(). The support is limited to binary modes only ('rb', 'wb', and 'rwb').
- CPython's arguments: ``encoding``, ``errors`` and ``newline`` are not supported.
+ CPython's arguments: *encoding*, *errors* and *newline* are not supported.
.. admonition:: Difference to CPython
:class: attention
- As MicroPython doesn't support buffered streams, values of ``buffering``
+ As MicroPython doesn't support buffered streams, values of *buffering*
parameter is ignored and treated as if it was 0 (unbuffered).
.. admonition:: Difference to CPython
@@ -220,19 +252,19 @@ Methods
.. method:: socket.read([size])
- Read up to size bytes from the socket. Return a bytes object. If ``size`` is not given, it
- reads all data available from the socket until ``EOF``; as such the method will not return until
+ Read up to size bytes from the socket. Return a bytes object. If *size* is not given, it
+ reads all data available from the socket until EOF; as such the method will not return until
the socket is closed. This function tries to read as much data as
requested (no "short reads"). This may be not possible with
non-blocking socket though, and then less data will be returned.
.. method:: socket.readinto(buf[, nbytes])
- Read bytes into the ``buf``. If ``nbytes`` is specified then read at most
- that many bytes. Otherwise, read at most ``len(buf)`` bytes. Just as
- ``read()``, this method follows "no short reads" policy.
+ Read bytes into the *buf*. If *nbytes* is specified then read at most
+ that many bytes. Otherwise, read at most *len(buf)* bytes. Just as
+ `read()`, this method follows "no short reads" policy.
- Return value: number of bytes read and stored into ``buf``.
+ Return value: number of bytes read and stored into *buf*.
.. method:: socket.readline()
@@ -245,6 +277,16 @@ Methods
Write the buffer of bytes to the socket. This function will try to
write all data to a socket (no "short writes"). This may be not possible
with a non-blocking socket though, and returned value will be less than
- the length of ``buf``.
+ the length of *buf*.
Return value: number of bytes written.
+
+.. exception:: socket.error
+
+ MicroPython does NOT have this exception.
+
+ .. admonition:: Difference to CPython
+ :class: attention
+
+ CPython used to have a ``socket.error`` exception which is now deprecated,
+ and is an alias of `OSError`. In MicroPython, use `OSError` directly.
diff --git a/docs/library/ussl.rst b/docs/library/ussl.rst
index 36f6d65a4a..c71b283ccb 100644
--- a/docs/library/ussl.rst
+++ b/docs/library/ussl.rst
@@ -4,6 +4,8 @@
.. module:: ussl
:synopsis: TLS/SSL wrapper for socket objects
+|see_cpython_module| :mod:`python:ssl`.
+
This module provides access to Transport Layer Security (previously and
widely known as “Secure Sockets Layer”) encryption and peer authentication
facilities for network sockets, both client-side and server-side.
@@ -13,7 +15,7 @@ Functions
.. function:: ssl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE, ca_certs=None)
- Takes a stream `sock` (usually usocket.socket instance of ``SOCK_STREAM`` type),
+ Takes a stream *sock* (usually usocket.socket instance of ``SOCK_STREAM`` type),
and returns an instance of ssl.SSLSocket, which wraps the underlying stream in
an SSL context. Returned object has the usual stream interface methods like
`read()`, `write()`, etc. In MicroPython, the returned object does not expose
@@ -43,4 +45,4 @@ Constants
ssl.CERT_OPTIONAL
ssl.CERT_REQUIRED
- Supported values for `cert_reqs` parameter.
+ Supported values for *cert_reqs* parameter.
diff --git a/docs/library/ustruct.rst b/docs/library/ustruct.rst
index 74e42af07a..81915d0a8d 100644
--- a/docs/library/ustruct.rst
+++ b/docs/library/ustruct.rst
@@ -4,8 +4,7 @@
.. module:: ustruct
:synopsis: pack and unpack primitive data types
-See `Python struct <https://docs.python.org/3/library/struct.html>`_ for more
-information.
+|see_cpython_module| :mod:`python:struct`.
Supported size/byte order prefixes: ``@``, ``<``, ``>``, ``!``.
@@ -18,26 +17,26 @@ Functions
.. function:: calcsize(fmt)
- Return the number of bytes needed to store the given `fmt`.
+ Return the number of bytes needed to store the given *fmt*.
.. function:: pack(fmt, v1, v2, ...)
- Pack the values `v1`, `v2`, ... according to the format string `fmt`.
+ Pack the values *v1*, *v2*, ... according to the format string *fmt*.
The return value is a bytes object encoding the values.
.. function:: pack_into(fmt, buffer, offset, v1, v2, ...)
- Pack the values `v1`, `v2`, ... according to the format string `fmt`
- into a `buffer` starting at `offset`. `offset` may be negative to count
- from the end of `buffer`.
+ Pack the values *v1*, *v2*, ... according to the format string *fmt*
+ into a *buffer* starting at *offset*. *offset* may be negative to count
+ from the end of *buffer*.
.. function:: unpack(fmt, data)
- Unpack from the `data` according to the format string `fmt`.
+ Unpack from the *data* according to the format string *fmt*.
The return value is a tuple of the unpacked values.
.. function:: unpack_from(fmt, data, offset=0)
- Unpack from the `data` starting at `offset` according to the format string
- `fmt`. `offset` may be negative to count from the end of `buffer`. The return
+ Unpack from the *data* starting at *offset* according to the format string
+ *fmt*. *offset* may be negative to count from the end of *buffer*. The return
value is a tuple of the unpacked values.
diff --git a/docs/library/utime.rst b/docs/library/utime.rst
index f3a067cdef..a39f5ee733 100644
--- a/docs/library/utime.rst
+++ b/docs/library/utime.rst
@@ -4,6 +4,8 @@
.. module:: utime
:synopsis: time related functions
+|see_cpython_module| :mod:`python:time`.
+
The ``utime`` module provides functions for getting the current time and date,
measuring time intervals, and for delays.
@@ -57,10 +59,10 @@ Functions
.. function:: sleep(seconds)
- Sleep for the given number of seconds. Some boards may accept `seconds` as a
+ Sleep for the given number of seconds. Some boards may accept *seconds* as a
floating-point number to sleep for a fractional number of seconds. Note that
other boards may not accept a floating-point argument, for compatibility with
- them use ``sleep_ms()`` and ``sleep_us()`` functions.
+ them use `sleep_ms()` and `sleep_us()` functions.
.. function:: sleep_ms(ms)
@@ -73,30 +75,32 @@ Functions
.. function:: ticks_ms()
Returns an increasing millisecond counter with an arbitrary reference point, that
- wraps around after some value. This value is not explicitly exposed, but we will
- refer to it as ``TICKS_MAX`` to simplify discussion. Period of the values is
- ``TICKS_PERIOD = TICKS_MAX + 1``. ``TICKS_PERIOD`` is guaranteed to be a power of
+ wraps around after some value.
+
+ The wrap-around value is not explicitly exposed, but we will
+ refer to it as *TICKS_MAX* to simplify discussion. Period of the values is
+ *TICKS_PERIOD = TICKS_MAX + 1*. *TICKS_PERIOD* is guaranteed to be a power of
two, but otherwise may differ from port to port. The same period value is used
- for all of ``ticks_ms()``, ``ticks_us()``, ``ticks_cpu()`` functions (for
- simplicity). Thus, these functions will return a value in range [``0`` ..
- ``TICKS_MAX``], inclusive, total ``TICKS_PERIOD`` values. Note that only
+ for all of `ticks_ms()`, `ticks_us()`, `ticks_cpu()` functions (for
+ simplicity). Thus, these functions will return a value in range [*0* ..
+ *TICKS_MAX*], inclusive, total *TICKS_PERIOD* values. Note that only
non-negative values are used. For the most part, you should treat values returned
by these functions as opaque. The only operations available for them are
- ``ticks_diff()`` and ``ticks_add()`` functions described below.
+ `ticks_diff()` and `ticks_add()` functions described below.
Note: Performing standard mathematical operations (+, -) or relational
operators (<, <=, >, >=) directly on these value will lead to invalid
result. Performing mathematical operations and then passing their results
- as arguments to ``ticks_diff()`` or ``ticks_add()`` will also lead to
+ as arguments to `ticks_diff()` or `ticks_add()` will also lead to
invalid results from the latter functions.
.. function:: ticks_us()
- Just like ``ticks_ms()`` above, but in microseconds.
+ Just like `ticks_ms()` above, but in microseconds.
.. function:: ticks_cpu()
- Similar to ``ticks_ms()`` and ``ticks_us()``, but with the highest possible resolution
+ Similar to `ticks_ms()` and `ticks_us()`, but with the highest possible resolution
in the system. This is usually CPU clocks, and that's why the function is named that
way. But it doesn't have to be a CPU clock, some other timing source available in a
system (e.g. high-resolution timer) can be used instead. The exact timing unit
@@ -111,13 +115,13 @@ Functions
.. function:: ticks_add(ticks, delta)
Offset ticks value by a given number, which can be either positive or negative.
- Given a ``ticks`` value, this function allows to calculate ticks value ``delta``
+ Given a *ticks* value, this function allows to calculate ticks value *delta*
ticks before or after it, following modular-arithmetic definition of tick values
- (see ``ticks_ms()`` above). ``ticks`` parameter must be a direct result of call
- to ``ticks_ms()``, ``ticks_us()``, or ``ticks_cpu()`` functions (or from previous
- call to ``ticks_add()``). However, ``delta`` can be an arbitrary integer number
- or numeric expression. ``ticks_add()`` is useful for calculating deadlines for
- events/tasks. (Note: you must use ``ticks_diff()`` function to work with
+ (see `ticks_ms()` above). *ticks* parameter must be a direct result of call
+ to `ticks_ms()`, `ticks_us()`, or `ticks_cpu()` functions (or from previous
+ call to `ticks_add()`). However, *delta* can be an arbitrary integer number
+ or numeric expression. `ticks_add()` is useful for calculating deadlines for
+ events/tasks. (Note: you must use `ticks_diff()` function to work with
deadlines.)
Examples::
@@ -136,23 +140,25 @@ Functions
.. function:: ticks_diff(ticks1, ticks2)
- Measure ticks difference between values returned from ``ticks_ms()``, ``ticks_us()``,
- or ``ticks_cpu()`` functions. The argument order is the same as for subtraction
+ Measure ticks difference between values returned from `ticks_ms()`, `ticks_us()`,
+ or `ticks_cpu()` functions, as a signed value which may wrap around.
+
+ The argument order is the same as for subtraction
operator, ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``.
- However, values returned by ``ticks_ms()``, etc. functions may wrap around, so
+ However, values returned by `ticks_ms()`, etc. functions may wrap around, so
directly using subtraction on them will produce incorrect result. That is why
- ``ticks_diff()`` is needed, it implements modular (or more specifically, ring)
+ `ticks_diff()` is needed, it implements modular (or more specifically, ring)
arithmetics to produce correct result even for wrap-around values (as long as they not
too distant inbetween, see below). The function returns **signed** value in the range
- [``-TICKS_PERIOD/2`` .. ``TICKS_PERIOD/2-1``] (that's a typical range definition for
+ [*-TICKS_PERIOD/2* .. *TICKS_PERIOD/2-1*] (that's a typical range definition for
two's-complement signed binary integers). If the result is negative, it means that
- ``ticks1`` occurred earlier in time than ``ticks2``. Otherwise, it means that
- ``ticks1`` occurred after ``ticks2``. This holds ``only`` if ``ticks1`` and ``ticks2``
- are apart from each other for no more than ``TICKS_PERIOD/2-1`` ticks. If that does
+ *ticks1* occurred earlier in time than *ticks2*. Otherwise, it means that
+ *ticks1* occurred after *ticks2*. This holds **only** if *ticks1* and *ticks2*
+ are apart from each other for no more than *TICKS_PERIOD/2-1* ticks. If that does
not hold, incorrect result will be returned. Specifically, if two tick values are
- apart for ``TICKS_PERIOD/2-1`` ticks, that value will be returned by the function.
- However, if ``TICKS_PERIOD/2`` of real-time ticks has passed between them, the
- function will return ``-TICKS_PERIOD/2`` instead, i.e. result value will wrap around
+ apart for *TICKS_PERIOD/2-1* ticks, that value will be returned by the function.
+ However, if *TICKS_PERIOD/2* of real-time ticks has passed between them, the
+ function will return *-TICKS_PERIOD/2* instead, i.e. result value will wrap around
to the negative range of possible values.
Informal rationale of the constraints above: Suppose you are locked in a room with no
@@ -164,10 +170,10 @@ Functions
behavior: don't let your application run any single task for too long. Run tasks
in steps, and do time-keeping inbetween.
- ``ticks_diff()`` is designed to accommodate various usage patterns, among them:
+ `ticks_diff()` is designed to accommodate various usage patterns, among them:
- Polling with timeout. In this case, the order of events is known, and you will deal
- only with positive results of ``ticks_diff()``::
+ * Polling with timeout. In this case, the order of events is known, and you will deal
+ only with positive results of `ticks_diff()`::
# Wait for GPIO pin to be asserted, but at most 500us
start = time.ticks_us()
@@ -175,8 +181,8 @@ Functions
if time.ticks_diff(time.ticks_us(), start) > 500:
raise TimeoutError
- Scheduling events. In this case, ``ticks_diff()`` result may be negative
- if an event is overdue::
+ * Scheduling events. In this case, `ticks_diff()` result may be negative
+ if an event is overdue::
# This code snippet is not optimized
now = time.ticks_ms()
@@ -192,8 +198,8 @@ Functions
print("Oops, running late, tell task to run faster!")
task.run(run_faster=true)
- Note: Do not pass ``time()`` values to ``ticks_diff()``, you should use
- normal mathematical operations on them. But note that ``time()`` may (and will)
+ Note: Do not pass `time()` values to `ticks_diff()`, you should use
+ normal mathematical operations on them. But note that `time()` may (and will)
also overflow. This is known as https://en.wikipedia.org/wiki/Year_2038_problem .
@@ -205,8 +211,8 @@ Functions
embedded boards without a battery-backed RTC, usually since power up or reset). If you
want to develop portable MicroPython application, you should not rely on this function
to provide higher than second precision. If you need higher precision, use
- ``ticks_ms()`` and ``ticks_us()`` functions, if you need calendar time,
- ``localtime()`` without an argument is a better choice.
+ `ticks_ms()` and `ticks_us()` functions, if you need calendar time,
+ `localtime()` without an argument is a better choice.
.. admonition:: Difference to CPython
:class: attention
diff --git a/docs/library/uzlib.rst b/docs/library/uzlib.rst
index 8775ec3e07..fb1746fe8e 100644
--- a/docs/library/uzlib.rst
+++ b/docs/library/uzlib.rst
@@ -4,13 +4,35 @@
.. module:: uzlib
:synopsis: zlib decompression
-This modules allows to decompress binary data compressed with DEFLATE
-algorithm (commonly used in zlib library and gzip archiver). Compression
+|see_cpython_module| :mod:`python:zlib`.
+
+This module allows to decompress binary data compressed with
+`DEFLATE algorithm <https://en.wikipedia.org/wiki/DEFLATE>`_
+(commonly used in zlib library and gzip archiver). Compression
is not yet implemented.
Functions
---------
-.. function:: decompress(data)
+.. function:: decompress(data, wbits=0, bufsize=0)
+
+ Return decompressed *data* as bytes. *wbits* is DEFLATE dictionary window
+ size used during compression (8-15, the dictionary size is power of 2 of
+ that value). Additionally, if value is positive, *data* is assumed to be
+ zlib stream (with zlib header). Otherwise, if it's negative, it's assumed
+ to be raw DEFLATE stream. *bufsize* parameter is for compatibility with
+ CPython and is ignored.
+
+.. class:: DecompIO(stream, wbits=0)
+
+ Create a stream wrapper which allows transparent decompression of
+ compressed data in another *stream*. This allows to process compressed
+ streams with data larger than available heap size. In addition to
+ values described in :func:`decompress`, *wbits* may take values
+ 24..31 (16 + 8..15), meaning that input stream has gzip header.
+
+ .. admonition:: Difference to CPython
+ :class: attention
- Return decompressed data as bytes.
+ This class is MicroPython extension. It's included on provisional
+ basis and may be changed considerably or removed in later versions.