all: Update Python formatting to ruff-format.

This updates a small number of files that change with ruff-format's (vs
black's) rules.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
This commit is contained in:
Jim Mussared 2023-10-21 17:40:27 +11:00 committed by Damien George
parent 303ccca7c6
commit bbd8760bd9
9 changed files with 160 additions and 131 deletions

View File

@ -19,23 +19,21 @@ import os
# If extensions (or modules to document with autodoc) are in another directory, # If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the # add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here. # documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath("."))
# The MICROPY_VERSION env var should be "vX.Y.Z" (or unset). # The MICROPY_VERSION env var should be "vX.Y.Z" (or unset).
micropy_version = os.getenv('MICROPY_VERSION') or 'latest' micropy_version = os.getenv("MICROPY_VERSION") or "latest"
micropy_all_versions = (os.getenv('MICROPY_ALL_VERSIONS') or 'latest').split(',') micropy_all_versions = (os.getenv("MICROPY_ALL_VERSIONS") or "latest").split(",")
url_pattern = '%s/en/%%s' % (os.getenv('MICROPY_URL_PREFIX') or '/',) url_pattern = "%s/en/%%s" % (os.getenv("MICROPY_URL_PREFIX") or "/",)
# The members of the html_context dict are available inside topindex.html # The members of the html_context dict are available inside topindex.html
html_context = { html_context = {
'cur_version':micropy_version, "cur_version": micropy_version,
'all_versions':[ "all_versions": [(ver, url_pattern % ver) for ver in micropy_all_versions],
(ver, url_pattern % ver) for ver in micropy_all_versions "downloads": [
("PDF", url_pattern % micropy_version + "/micropython-docs.pdf"),
], ],
'downloads':[ "is_release": micropy_version != "latest",
('PDF', url_pattern % micropy_version + '/micropython-docs.pdf'),
],
'is_release': micropy_version != 'latest',
} }
@ -48,29 +46,29 @@ html_context = {
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones. # ones.
extensions = [ extensions = [
'sphinx.ext.autodoc', "sphinx.ext.autodoc",
'sphinx.ext.doctest', "sphinx.ext.doctest",
'sphinx.ext.intersphinx', "sphinx.ext.intersphinx",
'sphinx.ext.todo', "sphinx.ext.todo",
'sphinx.ext.coverage', "sphinx.ext.coverage",
'sphinxcontrib.jquery', "sphinxcontrib.jquery",
] ]
# Add any paths that contain templates here, relative to this directory. # Add any paths that contain templates here, relative to this directory.
templates_path = ['templates'] templates_path = ["templates"]
# The suffix of source filenames. # The suffix of source filenames.
source_suffix = '.rst' source_suffix = ".rst"
# The encoding of source files. # The encoding of source files.
# source_encoding = 'utf-8-sig' # source_encoding = 'utf-8-sig'
# The master toctree document. # The master toctree document.
master_doc = 'index' master_doc = "index"
# General information about the project. # General information about the project.
project = 'MicroPython' project = "MicroPython"
copyright = '- The MicroPython Documentation is Copyright © 2014-2023, Damien P. George, Paul Sokolovsky, and contributors' copyright = "- The MicroPython Documentation is Copyright © 2014-2023, Damien P. George, Paul Sokolovsky, and contributors"
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the # |version| and |release|, also used in various other places throughout the
@ -92,11 +90,11 @@ version = release = micropy_version
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
exclude_patterns = ['build', '.venv'] exclude_patterns = ["build", ".venv"]
# The reST default role (used for this markup: `text`) to use for all # The reST default role (used for this markup: `text`) to use for all
# documents. # documents.
default_role = 'any' default_role = "any"
# If true, '()' will be appended to :func: etc. cross-reference text. # If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True # add_function_parentheses = True
@ -110,7 +108,7 @@ default_role = 'any'
# show_authors = False # show_authors = False
# The name of the Pygments (syntax highlighting) style to use. # The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx' pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting. # A list of ignored prefixes for module index sorting.
# modindex_common_prefix = [] # modindex_common_prefix = []
@ -128,18 +126,19 @@ rst_epilog = """
# -- Options for HTML output ---------------------------------------------- # -- Options for HTML output ----------------------------------------------
# on_rtd is whether we are on readthedocs.org # on_rtd is whether we are on readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True' on_rtd = os.environ.get("READTHEDOCS", None) == "True"
if not on_rtd: # only import and set the theme if we're building docs locally if not on_rtd: # only import and set the theme if we're building docs locally
try: try:
import sphinx_rtd_theme import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.'] html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."]
except: except:
html_theme = 'default' html_theme = "default"
html_theme_path = ['.'] html_theme_path = ["."]
else: else:
html_theme_path = ['.'] html_theme_path = ["."]
# Theme options are theme-specific and customize the look and feel of a theme # Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the # further. For a list of options available for each theme, see the
@ -163,16 +162,16 @@ else:
# The name of an image file (within the static path) to use as favicon of the # The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large. # pixels large.
html_favicon = 'static/favicon.ico' html_favicon = "static/favicon.ico"
# Add any paths that contain custom static files (such as style sheets) here, # Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files, # relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css". # so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['static'] html_static_path = ["static"]
# Add a custom CSS file for HTML generation # Add a custom CSS file for HTML generation
html_css_files = [ html_css_files = [
'custom.css', "custom.css",
] ]
# Add any extra paths that contain custom files (such as robots.txt or # Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied # .htaccess) here, relative to this directory. These files are copied
@ -181,7 +180,7 @@ html_css_files = [
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format. # using the given strftime format.
html_last_updated_fmt = '%d %b %Y' html_last_updated_fmt = "%d %b %Y"
# If true, SmartyPants will be used to convert quotes and dashes to # If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities. # typographically correct entities.
@ -221,7 +220,7 @@ html_additional_pages = {"index": "topindex.html"}
# html_file_suffix = None # html_file_suffix = None
# Output file base name for HTML help builder. # Output file base name for HTML help builder.
htmlhelp_basename = 'MicroPythondoc' htmlhelp_basename = "MicroPythondoc"
# -- Options for LaTeX output --------------------------------------------- # -- Options for LaTeX output ---------------------------------------------
@ -229,22 +228,25 @@ htmlhelp_basename = 'MicroPythondoc'
latex_elements = { latex_elements = {
# The paper size ('letterpaper' or 'a4paper'). # The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper', #'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt'). # The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt', #'pointsize': '10pt',
# Additional stuff for the LaTeX preamble. # Additional stuff for the LaTeX preamble.
#'preamble': '', #'preamble': '',
# Include 3 levels of headers in PDF ToC # Include 3 levels of headers in PDF ToC
'preamble': r'\setcounter{tocdepth}{2}', "preamble": r"\setcounter{tocdepth}{2}",
} }
# Grouping the document tree into LaTeX files. List of tuples # Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, # (source start file, target name, title,
# author, documentclass [howto, manual, or own class]). # author, documentclass [howto, manual, or own class]).
latex_documents = [ latex_documents = [
(master_doc, 'MicroPython.tex', 'MicroPython Documentation', (
'Damien P. George, Paul Sokolovsky, and contributors', 'manual'), master_doc,
"MicroPython.tex",
"MicroPython Documentation",
"Damien P. George, Paul Sokolovsky, and contributors",
"manual",
),
] ]
# The name of an image file (relative to this directory) to place at the top of # The name of an image file (relative to this directory) to place at the top of
@ -275,8 +277,13 @@ latex_engine = "xelatex"
# One entry per manual page. List of tuples # One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section). # (source start file, name, description, authors, manual section).
man_pages = [ man_pages = [
('index', 'micropython', 'MicroPython Documentation', (
['Damien P. George, Paul Sokolovsky, and contributors'], 1), "index",
"micropython",
"MicroPython Documentation",
["Damien P. George, Paul Sokolovsky, and contributors"],
1,
),
] ]
# If true, show URL addresses after external links. # If true, show URL addresses after external links.
@ -289,9 +296,15 @@ man_pages = [
# (source start file, target name, title, author, # (source start file, target name, title, author,
# dir menu entry, description, category) # dir menu entry, description, category)
texinfo_documents = [ texinfo_documents = [
(master_doc, 'MicroPython', 'MicroPython Documentation', (
'Damien P. George, Paul Sokolovsky, and contributors', 'MicroPython', 'One line description of project.', master_doc,
'Miscellaneous'), "MicroPython",
"MicroPython Documentation",
"Damien P. George, Paul Sokolovsky, and contributors",
"MicroPython",
"One line description of project.",
"Miscellaneous",
),
] ]
# Documents to append as an appendix to all manuals. # Documents to append as an appendix to all manuals.
@ -308,4 +321,4 @@ texinfo_documents = [
# Example configuration for intersphinx: refer to the Python standard library. # Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'python': ('https://docs.python.org/3.5', None)} intersphinx_mapping = {"python": ("https://docs.python.org/3.5", None)}

View File

@ -1,9 +1,10 @@
import os import os
# Directory that the project lives in, aka ../.. # Directory that the project lives in, aka ../..
SITE_ROOT = '/'.join(os.path.dirname(__file__).split('/')[0:-2]) SITE_ROOT = "/".join(os.path.dirname(__file__).split("/")[0:-2])
TEMPLATE_DIRS = ( TEMPLATE_DIRS = (
"%s/templates/" % SITE_ROOT, # Your custom template directory, before the RTD one to override it. "%s/templates/"
% SITE_ROOT, # Your custom template directory, before the RTD one to override it.
"%s/readthedocs/templates/" % SITE_ROOT, # Default RTD template dir "%s/readthedocs/templates/" % SITE_ROOT, # Default RTD template dir
) )

View File

@ -32,7 +32,7 @@ class PIOASMEmit:
autopull=False, autopull=False,
push_thresh=32, push_thresh=32,
pull_thresh=32, pull_thresh=32,
fifo_join=0 fifo_join=0,
): ):
# array is a built-in module so importing it here won't require # array is a built-in module so importing it here won't require
# scanning the filesystem. # scanning the filesystem.

View File

@ -114,7 +114,14 @@ def ipcc_init():
SYS_CMD_BUF = get_ipcc_table_word(TABLE_SYS, 0) SYS_CMD_BUF = get_ipcc_table_word(TABLE_SYS, 0)
SYS_SYS_QUEUE = get_ipcc_table_word(TABLE_SYS, 1) SYS_SYS_QUEUE = get_ipcc_table_word(TABLE_SYS, 1)
global MM_BLE_SPARE_EVT_BUF, MM_SYS_SPARE_EVT_BUF, MM_BLE_POOL, MM_BLE_POOL_SIZE, MM_FREE_BUF_QUEUE, MM_EV_POOL, MM_EV_POOL_SIZE global \
MM_BLE_SPARE_EVT_BUF, \
MM_SYS_SPARE_EVT_BUF, \
MM_BLE_POOL, \
MM_BLE_POOL_SIZE, \
MM_FREE_BUF_QUEUE, \
MM_EV_POOL, \
MM_EV_POOL_SIZE
MM_BLE_SPARE_EVT_BUF = get_ipcc_table_word(TABLE_MEM_MANAGER, 0) MM_BLE_SPARE_EVT_BUF = get_ipcc_table_word(TABLE_MEM_MANAGER, 0)
MM_SYS_SPARE_EVT_BUF = get_ipcc_table_word(TABLE_MEM_MANAGER, 1) MM_SYS_SPARE_EVT_BUF = get_ipcc_table_word(TABLE_MEM_MANAGER, 1)
MM_BLE_POOL = get_ipcc_table_word(TABLE_MEM_MANAGER, 2) MM_BLE_POOL = get_ipcc_table_word(TABLE_MEM_MANAGER, 2)

View File

@ -15,65 +15,67 @@ import subprocess
import sys import sys
import types import types
def create_zip(zip_filename, zip_dir): def create_zip(zip_filename, zip_dir):
abs_zip_filename = os.path.abspath(zip_filename) abs_zip_filename = os.path.abspath(zip_filename)
save_cwd = os.getcwd() save_cwd = os.getcwd()
os.chdir(zip_dir) os.chdir(zip_dir)
if os.path.exists(abs_zip_filename): if os.path.exists(abs_zip_filename):
os.remove(abs_zip_filename) os.remove(abs_zip_filename)
subprocess.check_call(['zip', '-0', '-r', '-D', abs_zip_filename, '.']) subprocess.check_call(["zip", "-0", "-r", "-D", abs_zip_filename, "."])
os.chdir(save_cwd) os.chdir(save_cwd)
def create_c_from_file(c_filename, zip_filename): def create_c_from_file(c_filename, zip_filename):
with open(zip_filename, 'rb') as zip_file: with open(zip_filename, "rb") as zip_file:
with open(c_filename, 'wb') as c_file: with open(c_filename, "wb") as c_file:
print('#include <stdint.h>', file=c_file) print("#include <stdint.h>", file=c_file)
print('', file=c_file) print("", file=c_file)
print('const uint8_t memzip_data[] = {', file=c_file) print("const uint8_t memzip_data[] = {", file=c_file)
while True: while True:
buf = zip_file.read(16) buf = zip_file.read(16)
if not buf: if not buf:
break break
print(' ', end='', file=c_file) print(" ", end="", file=c_file)
for byte in buf: for byte in buf:
if isinstance(byte, types.StringType): if isinstance(byte, types.StringType):
print(' 0x{:02x},'.format(ord(byte)), end='', file=c_file) print(" 0x{:02x},".format(ord(byte)), end="", file=c_file)
else: else:
print(' 0x{:02x},'.format(byte), end='', file=c_file) print(" 0x{:02x},".format(byte), end="", file=c_file)
print('', file=c_file) print("", file=c_file)
print('};', file=c_file) print("};", file=c_file)
def main(): def main():
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
prog='make-memzip.py', prog="make-memzip.py",
usage='%(prog)s [options] [command]', usage="%(prog)s [options] [command]",
description='Generates a C source memzip file.' description="Generates a C source memzip file.",
) )
parser.add_argument( parser.add_argument(
'-z', '--zip-file', "-z",
dest='zip_filename', "--zip-file",
help='Specifies the name of the created zip file.', dest="zip_filename",
default='memzip_files.zip' help="Specifies the name of the created zip file.",
default="memzip_files.zip",
) )
parser.add_argument( parser.add_argument(
'-c', '--c-file', "-c",
dest='c_filename', "--c-file",
help='Specifies the name of the created C source file.', dest="c_filename",
default='memzip_files.c' help="Specifies the name of the created C source file.",
) default="memzip_files.c",
parser.add_argument(
dest='source_dir',
default='memzip_files'
) )
parser.add_argument(dest="source_dir", default="memzip_files")
args = parser.parse_args(sys.argv[1:]) args = parser.parse_args(sys.argv[1:])
print('args.zip_filename =', args.zip_filename) print("args.zip_filename =", args.zip_filename)
print('args.c_filename =', args.c_filename) print("args.c_filename =", args.c_filename)
print('args.source_dir =', args.source_dir) print("args.source_dir =", args.source_dir)
create_zip(args.zip_filename, args.source_dir) create_zip(args.zip_filename, args.source_dir)
create_c_from_file(args.c_filename, args.zip_filename) create_c_from_file(args.c_filename, args.zip_filename)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -136,6 +136,4 @@ def singleTraj(system, trajStart, h=0.02, tend=1.0):
# phaseDiagram(sysSM, (lambda i, j: [0.354, 0.654, 1.278, 0.8 + 0.2 * i, 0.1 + 0.1 * j]), (lambda a: (a[4], a[5])), h=0.1, tend=math.log(10**17)) # phaseDiagram(sysSM, (lambda i, j: [0.354, 0.654, 1.278, 0.8 + 0.2 * i, 0.1 + 0.1 * j]), (lambda a: (a[4], a[5])), h=0.1, tend=math.log(10**17))
# initial conditions at M_Z # initial conditions at M_Z
singleTraj( singleTraj(sysSM, [0.354, 0.654, 1.278, 0.983, 0.131], h=0.5, tend=math.log(10**17)) # true values
sysSM, [0.354, 0.654, 1.278, 0.983, 0.131], h=0.5, tend=math.log(10**17)
) # true values

View File

@ -331,7 +331,7 @@ class SerialTransport(Transport):
def fs_stat(self, src): def fs_stat(self, src):
try: try:
self.exec("import os") self.exec("import os")
return os.stat_result(self.eval("os.stat(%s)" % (("'%s'" % src)), parse=True)) return os.stat_result(self.eval("os.stat(%s)" % ("'%s'" % src), parse=True))
except TransportError as e: except TransportError as e:
reraise_filesystem_error(e, src) reraise_filesystem_error(e, src)

View File

@ -1454,7 +1454,15 @@ def freeze_mpy(firmware_qstr_idents, compiled_modules):
# As in qstr.c, set so that the first dynamically allocated pool is twice this size; must be <= the len # As in qstr.c, set so that the first dynamically allocated pool is twice this size; must be <= the len
qstr_pool_alloc = min(len(new), 10) qstr_pool_alloc = min(len(new), 10)
global bc_content, const_str_content, const_int_content, const_obj_content, const_table_qstr_content, const_table_ptr_content, raw_code_count, raw_code_content global \
bc_content, \
const_str_content, \
const_int_content, \
const_obj_content, \
const_table_qstr_content, \
const_table_ptr_content, \
raw_code_count, \
raw_code_content
qstr_content = 0 qstr_content = 0
bc_content = 0 bc_content = 0
const_str_content = 0 const_str_content = 0

View File

@ -546,7 +546,7 @@ class Pyboard:
def fs_stat(self, src): def fs_stat(self, src):
try: try:
self.exec_("import os") self.exec_("import os")
return os.stat_result(self.eval("os.stat(%s)" % (("'%s'" % src)), parse=True)) return os.stat_result(self.eval("os.stat(%s)" % ("'%s'" % src), parse=True))
except PyboardError as e: except PyboardError as e:
raise e.convert(src) raise e.convert(src)