SF.net SVN: docutils:[9840 ] trunk/docutils

aa-turner--- via Docutils-checkins <[email protected]>
Newsgroups gmane.text.docutils.cvs
Message-ID <[email protected]>
Revision: 9840
          http://sourceforge.net/p/docutils/code/9840
Author:   aa-turner
Date:     2024-08-01 21:56:03 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
Enable the flake8-builtins linter in Ruff

Modified Paths:
--------------
    trunk/docutils/.ruff.toml
    trunk/docutils/docutils/core.py
    trunk/docutils/docutils/nodes.py
    trunk/docutils/docutils/parsers/rst/directives/admonitions.py
    trunk/docutils/docutils/parsers/rst/states.py
    trunk/docutils/docutils/statemachine.py
    trunk/docutils/docutils/transforms/peps.py
    trunk/docutils/docutils/utils/math/math2html.py
    trunk/docutils/docutils/writers/odf_odt/__init__.py
    trunk/docutils/test/alltests.py
    trunk/docutils/test/test_io.py
    trunk/docutils/test/test_nodes.py
    trunk/docutils/test/test_utils/test__init__.py
    trunk/docutils/tools/dev/quicktest.py
    trunk/docutils/tools/dev/unicode2rstsubs.py

Modified: trunk/docutils/.ruff.toml
===================================================================
--- trunk/docutils/.ruff.toml	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/.ruff.toml	2024-08-01 21:56:03 UTC (rev 9840)
@@ -5,6 +5,7 @@
 [lint]
 preview = true
 select = [
+    "A",    # flake8-builtins
     "C4",   # flake8-comprehensions
     "E",    # pycodestyle
     "EXE",  # flake8-executable
@@ -77,6 +78,8 @@
 
 # module with 3rd-party origin
 "docutils/utils/math/math2html.py" = [
+    "A001",  # 'type' is used very frequently
+    "A002",  # 'type' is used very frequently
     "E241",
     "E501",
     "E731",
@@ -169,3 +172,9 @@
 "tools/dev/generate_punctuation_chars.py" = [
     "E501",
 ]
+
+[lint.flake8-builtins]
+builtins-ignorelist = [
+    "format",
+    "id",
+]

Modified: trunk/docutils/docutils/core.py
===================================================================
--- trunk/docutils/docutils/core.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/core.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -247,7 +247,7 @@
         already set), run `self.reader` and then `self.writer`.  Return
         `self.writer`'s output.
         """
-        exit = None
+        exit_ = None
         try:
             if self.settings is None:
                 self.process_command_line(
@@ -261,7 +261,7 @@
             output = self.writer.write(self.document, self.destination)
             self.writer.assemble_parts()
         except SystemExit as error:
-            exit = True
+            exit_ = True
             exit_status = error.code
         except Exception as error:
             if not self.settings:       # exception too early to report nicely
@@ -270,7 +270,7 @@
                 self.debugging_dumps()
                 raise
             self.report_Exception(error)
-            exit = True
+            exit_ = True
             exit_status = 1
         self.debugging_dumps()
         if (enable_exit_status and self.document
@@ -277,7 +277,7 @@
             and (self.document.reporter.max_level
                  >= self.settings.exit_status_level)):
             sys.exit(self.document.reporter.max_level + 10)
-        elif exit:
+        elif exit_:
             sys.exit(exit_status)
         return output
 

Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/nodes.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -1357,16 +1357,16 @@
     ) -> str:
         # Return a str reporting a missing child or child of wrong category.
         try:
-            type = category.__name__
+            type_ = category.__name__
         except AttributeError:
-            type = '> or <'.join(c.__name__ for c in category)
+            type_ = '> or <'.join(c.__name__ for c in category)
         msg = f'Element {self.starttag()} invalid:\n'
         if child is None:
-            return f'{msg}  Missing child of type <{type}>.'
+            return f'{msg}  Missing child of type <{type_}>.'
         if isinstance(child, Text):
-            return (f'{msg}  Expecting child of type <{type}>, '
+            return (f'{msg}  Expecting child of type <{type_}>, '
                     f'not text data "{child.astext()}".')
-        return (f'{msg}  Expecting child of type <{type}>, '
+        return (f'{msg}  Expecting child of type <{type_}>, '
                 f'not {child.starttag()}.')
 
     def check_position(self) -> None:
@@ -2172,7 +2172,7 @@
 class revision(Bibliographic, TextElement): pass
 class status(Bibliographic, TextElement): pass
 class date(Bibliographic, TextElement): pass
-class copyright(Bibliographic, TextElement): pass
+class copyright(Bibliographic, TextElement): pass  # NoQA: A001
 
 
 class authors(Bibliographic, Element):

Modified: trunk/docutils/docutils/parsers/rst/directives/admonitions.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/directives/admonitions.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/parsers/rst/directives/admonitions.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -96,6 +96,6 @@
     node_class = nodes.tip
 
 
-class Warning(BaseAdmonition):
+class Warning(BaseAdmonition):  # NoQA: A001
 
     node_class = nodes.warning

Modified: trunk/docutils/docutils/parsers/rst/states.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/states.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/parsers/rst/states.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -434,7 +434,7 @@
                                      line=lineno)
 
 
-def build_regexp(definition, compile=True):
+def build_regexp(definition, compile_patterns=True):
     """
     Build, compile and return a regular expression based on `definition`.
 
@@ -451,7 +451,7 @@
             part_strings.append(part)
     or_group = '|'.join(part_strings)
     regexp = '%(prefix)s(?P<%(name)s>%(or_group)s)%(suffix)s' % locals()
-    if compile:
+    if compile_patterns:
         return re.compile(regexp)
     else:
         return regexp

Modified: trunk/docutils/docutils/statemachine.py
===================================================================
--- trunk/docutils/docutils/statemachine.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/statemachine.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -477,8 +477,8 @@
 
     def error(self) -> None:
         """Report error details."""
-        type, value, module, line, function = _exception_data()
-        print('%s: %s' % (type, value), file=sys.stderr)
+        type_name, value, module, line, function = _exception_data()
+        print('%s: %s' % (type_name, value), file=sys.stderr)
         print('input line %s' % (self.abs_line_number()), file=sys.stderr)
         print('module %s, line %s, function %s' % (module, line, function),
               file=sys.stderr)
@@ -1525,9 +1525,9 @@
     - the line number of the offending code;
     - the function name of the offending code.
     """
-    type, value, traceback = sys.exc_info()
+    typ, value, traceback = sys.exc_info()
     while traceback.tb_next:
         traceback = traceback.tb_next
     code = traceback.tb_frame.f_code
-    return (type.__name__, value, code.co_filename, traceback.tb_lineno,
+    return (typ.__name__, value, code.co_filename, traceback.tb_lineno,
             code.co_name)

Modified: trunk/docutils/docutils/transforms/peps.py
===================================================================
--- trunk/docutils/docutils/transforms/peps.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/transforms/peps.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -174,7 +174,7 @@
     def apply(self) -> None:
         doc = self.document
         i = len(doc) - 1
-        refsect = copyright = None
+        refsect = copyright_ = None
         while i >= 0 and isinstance(doc[i], nodes.section):
             title_words = doc[i][0].astext().lower().split()
             if 'references' in title_words:
@@ -181,15 +181,15 @@
                 refsect = doc[i]
                 break
             elif 'copyright' in title_words:
-                copyright = i
+                copyright_ = i
             i -= 1
         if not refsect:
             refsect = nodes.section()
             refsect += nodes.title('', 'References')
             doc.set_id(refsect)
-            if copyright:
+            if copyright_:
                 # Put the new "References" section before "Copyright":
-                doc.insert(copyright, refsect)
+                doc.insert(copyright_, refsect)
             else:
                 # Put the new "References" section at end of doc:
                 doc.append(refsect)

Modified: trunk/docutils/docutils/utils/math/math2html.py
===================================================================
--- trunk/docutils/docutils/utils/math/math2html.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/utils/math/math2html.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -699,18 +699,18 @@
 
     def extract(self, container):
         "Extract a group of selected containers from a container."
-        list = []
+        lst = []
         locate = lambda c: c.__class__.__name__ in self.allowed
         recursive = lambda c: c.__class__.__name__ in self.extracted
-        process = lambda c: self.process(c, list)
+        process = lambda c: self.process(c, lst)
         container.recursivesearch(locate, recursive, process)
-        return list
+        return lst
 
-    def process(self, container, list) -> None:
+    def process(self, container, lst) -> None:
         "Add allowed containers."
         name = container.__class__.__name__
         if name in self.allowed:
-            list.append(container)
+            lst.append(container)
         else:
             Trace.error('Unknown container class ' + name)
 
@@ -944,10 +944,10 @@
         "Get opening line."
         if not self.checktag(container):
             return ''
-        open = '<' + self.tag + '>'
+        open_tag = '<' + self.tag + '>'
         if self.breaklines:
-            return open + '\n'
-        return open
+            return open_tag + '\n'
+        return open_tag
 
     def close(self, container):
         "Get closing line."
@@ -1355,16 +1355,16 @@
 
     def searchall(self, type):
         "Search for all embedded containers of a given type"
-        list = []
-        self.searchprocess(type, lambda container: list.append(container))
-        return list
+        lst = []
+        self.searchprocess(type, lambda container: lst.append(container))
+        return lst
 
     def searchremove(self, type):
         "Search for all containers of a type and remove them"
-        list = self.searchall(type)
-        for container in list:
+        lst = self.searchall(type)
+        for container in lst:
             container.parent.contents.remove(container)
-        return list
+        return lst
 
     def searchprocess(self, type, process) -> None:
         "Search for elements of a given type and process them"

Modified: trunk/docutils/docutils/writers/odf_odt/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/odf_odt/__init__.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/writers/odf_odt/__init__.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -291,13 +291,13 @@
     text = text.replace("&", "&amp;")
     text = text.replace("<", "&lt;")
     text = text.replace(">", "&gt;")
-    ascii = ''
+    ascii_ = ''
     for char in text:
         if ord(char) >= ord("\x7f"):
-            ascii += "&#x%X;" % (ord(char), )
+            ascii_ += "&#x%X;" % (ord(char), )
         else:
-            ascii += char
-    return ascii
+            ascii_ += char
+    return ascii_
 
 
 #
@@ -633,7 +633,7 @@
         return updated, stylesheet_root, modified_nodes
 
     def write_zip_str(
-        self, zfile, name, bytes, compress_type=zipfile.ZIP_DEFLATED,
+        self, zfile, name, bytes_, compress_type=zipfile.ZIP_DEFLATED,
     ) -> None:
         localtime = time.localtime(time.time())
         zinfo = zipfile.ZipInfo(name, localtime)
@@ -640,7 +640,7 @@
         # Add some standard UNIX file access permissions (-rw-r--r--).
         zinfo.external_attr = (0x81a4 & 0xFFFF) << 16
         zinfo.compress_type = compress_type
-        zfile.writestr(zinfo, bytes)
+        zfile.writestr(zinfo, bytes_)
 
     def store_embedded_files(self, zfile) -> None:
         embedded_files = self.visitor.get_embedded_file_list()
@@ -964,10 +964,10 @@
                 if family == 'table':
                     properties = stylenode.find(
                         '{%s}table-properties' % (CNSD['style'], ))
-                    property = properties.get(
+                    property_ = properties.get(
                         '{%s}%s' % (CNSD['fo'], 'background-color', ))
-                    if property is not None and property != 'none':
-                        tablestyle.backgroundcolor = property
+                    if property_ is not None and property_ != 'none':
+                        tablestyle.backgroundcolor = property_
                 elif family == 'table-cell':
                     properties = stylenode.find(
                         '{%s}table-cell-properties' % (CNSD['style'], ))

Modified: trunk/docutils/test/alltests.py
===================================================================
--- trunk/docutils/test/alltests.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/test/alltests.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -12,7 +12,7 @@
 All modules named 'test_*.py' in the current directory, and recursively in
 subdirectories (packages) called 'test_*', are loaded and test suites within
 are run.
-"""
+"""  # NoQA: A001
 
 import atexit
 import platform

Modified: trunk/docutils/test/test_io.py
===================================================================
--- trunk/docutils/test/test_io.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/test/test_io.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -115,41 +115,41 @@
         # default input encoding will change to UTF-8 in Docutils 0.22
         source = '\ufeffdata\n\ufeff blah\n'
         expected = 'data\n\ufeff blah\n'  # only leading ZWNBSP removed
-        input = du_io.StringInput(source=source.encode('utf-16-be'),
-                                  encoding=None)
-        self.assertEqual(expected, input.read())
-        input = du_io.StringInput(source=source.encode('utf-16-le'),
-                                  encoding=None)
-        self.assertEqual(expected, input.read())
-        input = du_io.StringInput(source=source.encode('utf-8'),
-                                  encoding=None)
-        self.assertEqual(expected, input.read())
+        input_ = du_io.StringInput(source=source.encode('utf-16-be'),
+                                   encoding=None)
+        self.assertEqual(expected, input_.read())
+        input_ = du_io.StringInput(source=source.encode('utf-16-le'),
+                                   encoding=None)
+        self.assertEqual(expected, input_.read())
+        input_ = du_io.StringInput(source=source.encode('utf-8'),
+                                   encoding=None)
+        self.assertEqual(expected, input_.read())
         # With `str` input all ZWNBSPs are still there.
-        input = du_io.StringInput(source=source)
-        self.assertEqual(source, input.read())
+        input_ = du_io.StringInput(source=source)
+        self.assertEqual(source, input_.read())
 
     def test_encoding_declaration(self):
-        input = du_io.StringInput(source=b"""\
+        input_ = du_io.StringInput(source=b"""\
 .. -*- coding: ascii -*-
 data
 blah
 """, encoding=None)
-        data = input.read()  # noqa: F841
-        self.assertEqual('ascii', input.successful_encoding)
-        input = du_io.StringInput(source=b"""\
+        data = input_.read()  # noqa: F841
+        self.assertEqual('ascii', input_.successful_encoding)
+        input_ = du_io.StringInput(source=b"""\
 #! python
 # -*- coding: ascii -*-
 print("hello world")
 """, encoding=None)
-        data = input.read()  # noqa: F841
-        self.assertEqual('ascii', input.successful_encoding)
-        input = du_io.StringInput(source=b"""\
+        data = input_.read()  # noqa: F841
+        self.assertEqual('ascii', input_.successful_encoding)
+        input_ = du_io.StringInput(source=b"""\
 #! python
 # extraneous comment; prevents coding slug from being read
 # -*- coding: ascii -*-
 print("hello world")
 """)
-        self.assertNotEqual(input.successful_encoding, 'ascii')
+        self.assertNotEqual(input_.successful_encoding, 'ascii')
 
     def test_decode_unicode(self):
         # With the special value "unicode" or "Unicode":

Modified: trunk/docutils/test/test_nodes.py
===================================================================
--- trunk/docutils/test/test_nodes.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/test/test_nodes.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -1084,8 +1084,8 @@
     def test_make_id(self):
         failures = []
         tests = self.ids + self.ids_unicode_all
-        for input, expect in tests:
-            output = nodes.make_id(input)
+        for input_, expect in tests:
+            output = nodes.make_id(input_)
             if expect != output:
                 failures.append("'%s' != '%s'" % (expect, output))
         if failures:

Modified: trunk/docutils/test/test_utils/test__init__.py
===================================================================
--- trunk/docutils/test/test_utils/test__init__.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/test/test_utils/test__init__.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -184,16 +184,16 @@
                   'empty': (lambda x: x)}
 
     def test_assemble_option_dict(self):
-        input = utils.extract_name_value('a=1 bbb=2.0 cdef=hol%s' % chr(224))
+        input_ = utils.extract_name_value('a=1 bbb=2.0 cdef=hol%s' % chr(224))
         self.assertEqual(
-              utils.assemble_option_dict(input, self.optionspec),
+              utils.assemble_option_dict(input_, self.optionspec),
               {'a': 1, 'bbb': 2.0, 'cdef': ('hol%s' % chr(224))})
-        input = utils.extract_name_value('a=1 b=2.0 c=hol%s' % chr(224))
+        input_ = utils.extract_name_value('a=1 b=2.0 c=hol%s' % chr(224))
         with self.assertRaises(KeyError):
-            utils.assemble_option_dict(input, self.optionspec)
-        input = utils.extract_name_value('a=1 bbb=two cdef=hol%s' % chr(224))
+            utils.assemble_option_dict(input_, self.optionspec)
+        input_ = utils.extract_name_value('a=1 bbb=two cdef=hol%s' % chr(224))
         with self.assertRaises(ValueError):
-            utils.assemble_option_dict(input, self.optionspec)
+            utils.assemble_option_dict(input_, self.optionspec)
 
     def test_extract_extension_options(self):
         field_list = nodes.field_list()

Modified: trunk/docutils/tools/dev/quicktest.py
===================================================================
--- trunk/docutils/tools/dev/quicktest.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/tools/dev/quicktest.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -108,19 +108,19 @@
 
 
 def _pretty(
-    input: str, document: nodes.document, optargs: _OptArgs,
+    input_: str, document: nodes.document, optargs: _OptArgs,
 ) -> str:
     return document.pformat()
 
 
 def _rawxml(
-    input: str, document: nodes.document, optargs: _OptArgs,
+    input_: str, document: nodes.document, optargs: _OptArgs,
 ) -> str:
     return document.asdom().toxml()
 
 
 def _styledxml(
-    input: str, document: nodes.document, optargs: _OptArgs,
+    input_: str, document: nodes.document, optargs: _OptArgs,
 ) -> str:
     docnode = document.asdom().childNodes[0]
     return '\n'.join(('<?xml version="1.0" encoding="ISO-8859-1"?>',
@@ -130,13 +130,13 @@
 
 
 def _prettyxml(
-    input: str, document: nodes.document, optargs: _OptArgs,
+    input_: str, document: nodes.document, optargs: _OptArgs,
 ) -> str:
     return document.asdom().toprettyxml('    ', '\n')
 
 
 def _test(
-    input: str, document: nodes.document, optargs: _OptArgs,
+    input_: str, document: nodes.document, optargs: _OptArgs,
 ) -> str:
     tq = '"""'
     output = document.pformat()         # same as _pretty()
@@ -149,7 +149,7 @@
 %s
 %s],
 ]
-""" % (tq, escape(input.rstrip()), tq, tq, escape(output.rstrip()), tq)
+""" % (tq, escape(input_.rstrip()), tq, tq, escape(output.rstrip()), tq)
 
 
 def escape(text: str) -> str:
@@ -173,12 +173,12 @@
 
 def format(
     output_format: str,
-    input: str,
+    input_: str,
     document: nodes.document,
     optargs: _OptArgs,
 ) -> str:
     formatter = _output_formatters[output_format]
-    return formatter(input, document, optargs)
+    return formatter(input_, document, optargs)
 
 
 def posix_get_args(argv: list[str]) -> tuple[TextIO, TextIO, str, _OptArgs]:
@@ -241,10 +241,10 @@
     settings = frontend.get_default_settings(Parser)
     settings.debug = optargs['debug']
     parser = Parser()
-    input = input_file.read()
+    input_ = input_file.read()
     document = new_document(input_file.name, settings)
-    parser.parse(input, document)
-    output = format(output_format, input, document, optargs)
+    parser.parse(input_, document)
+    output = format(output_format, input_, document, optargs)
     output_file.write(output)
     if optargs['attributes']:
         import pprint

Modified: trunk/docutils/tools/dev/unicode2rstsubs.py
===================================================================
--- trunk/docutils/tools/dev/unicode2rstsubs.py	2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/tools/dev/unicode2rstsubs.py	2024-08-01 21:56:03 UTC (rev 9840)
@@ -134,18 +134,18 @@
         self.charid = attributes['id']
 
     def entity_start(self, name, attributes) -> None:
-        set = self.entity_set_name(attributes['set'])
-        if not set:
+        set_ = self.entity_set_name(attributes['set'])
+        if not set_:
             return
-        if set not in self.sets:
-            print('bad set: %r' % set)
+        if set_ not in self.sets:
+            print('bad set: %r' % set_)
             return
         entity = attributes['id']
-        assert (entity not in self.sets[set]
-                or self.sets[set][entity] == self.charid
+        assert (entity not in self.sets[set_]
+                or self.sets[set_][entity] == self.charid
                 ), ('sets[%r][%r] == %r (!= %r)'
-                    % (set, entity, self.sets[set][entity], self.charid))
-        self.sets[set][entity] = self.charid
+                    % (set_, entity, self.sets[set_][entity], self.charid))
+        self.sets[set_][entity] = self.charid
 
     def description_data(self, data) -> None:
         self.descriptions.setdefault(self.charid, '')
@@ -179,8 +179,8 @@
         outfile = open(outname, 'w', encoding='ascii')
         print('writing file "%s"' % outname)
         outfile.write(self.header + '\n')
-        set = self.sets[set_name]
-        entities = sorted((e.lower(), e) for e in set.keys())
+        set_ = self.sets[set_name]
+        entities = sorted((e.lower(), e) for e in set_.keys())
         longest = 0
         for _, entity_name in entities:
             longest = max(longest, len(entity_name))
@@ -187,13 +187,14 @@
         has_wide = False
         for _, entity_name in entities:
             has_wide = self.write_entity(
-                set, set_name, entity_name, outfile, longest, wide) or has_wide
+                set_, set_name, entity_name, outfile, longest, wide,
+            ) or has_wide
         if has_wide and not wide:
             self.write_set(set_name, wide=True)
 
     def write_entity(
         self,
-        set: dict[str, str],
+        set_: dict[str, str],
         set_name: str,
         entity_name: str,
         outfile: TextIO,
@@ -200,7 +201,7 @@
         longest: int,
         wide: bool = False,
     ) -> bool:
-        charid = set[entity_name]
+        charid = set_[entity_name]
         if not wide:
             for code in charid[1:].split('-'):
                 if int(code, 16) > 0xFFFF:

This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.