diff options
author | Friedemann Kleint <Friedemann.Kleint@qt.io> | 2024-01-23 10:25:57 +0100 |
---|---|---|
committer | Friedemann Kleint <Friedemann.Kleint@qt.io> | 2024-01-24 11:58:02 +0100 |
commit | 69095b73ef5cef6237d90a6c327c220fc593f99c (patch) | |
tree | b986602546c653a24ebd4e6e5176084f1f68deb0 | |
parent | 602245bc1e1ae39dad6441315036d86e70a9b742 (diff) |
Fix flake8 warnings in shibokenmodule
Fix more than 200 warnings.
Change-Id: I2f3f7658d68e2100e20a84d98e0189488218d07e
Reviewed-by: Qt CI Bot <qt_ci_bot@qt-project.org>
Reviewed-by: Cristian Maureira-Fredes <cristian.maureira-fredes@qt.io>
10 files changed, 73 insertions, 51 deletions
diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/feature.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/feature.py index d403c7582..7a0871ee7 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/feature.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/feature.py @@ -1,6 +1,9 @@ # Copyright (C) 2022 The Qt Company Ltd. # SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +# flake8: noqa F:821 +# flake8: noqa F:401 + """ __feature__.py (renamed to feature.py) @@ -80,6 +83,7 @@ None to indicate that a normal import should be performed, and All these variables are transparently kept in module `builtins`. """ + def feature_import(name, *args, **kwargs): # PYSIDE-1368: The `__name__` attribute does not need to exist in all modules. # PYSIDE-1398: sys._getframe(1) may not exist when embedding. @@ -110,8 +114,10 @@ def feature_import(name, *args, **kwargs): # Redirect to the original import return None + _is_initialized = False + def __init__(): global _is_initialized if not _is_initialized: @@ -182,6 +188,7 @@ def set_selection(select_id, mod_name=None): sys.modules["PySide6.QtCore"].__init_feature__() return _current_selection(flag) + # The set_section(0) case seems to be unsafe. We will migrate to # use the opaque feature.reset() call in all test cases. def reset(): diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/fix-complaints.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/fix-complaints.py index 3e1d49328..f7190b12f 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/fix-complaints.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/fix-complaints.py @@ -9,7 +9,6 @@ Run it once after copying a new version. It is idem-potent, unless you are changing messages (what I did, of course :-) . """ -import os import glob from pathlib import Path @@ -24,6 +23,7 @@ offending_words = { utf8_line = "# This Python file uses the following encoding: utf-8\n" marker_line = f"# It has been edited by {Path(__file__).name} .\n" + def patch_file(fname): with fname.open() as f: lines = f.readlines() @@ -41,6 +41,7 @@ def patch_file(fname): with open(fname, "w") as f: f.write("".join(lines)) + def doit(): dirname = Path(__file__).parent patched_files = [] @@ -51,6 +52,7 @@ def doit(): print("Working on", fname) patch_file(fname) + if __name__ == "__main__": doit() diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/errorhandler.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/errorhandler.py index 5b63de45a..c2a19efef 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/errorhandler.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/errorhandler.py @@ -1,6 +1,8 @@ # Copyright (C) 2022 The Qt Company Ltd. # SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +# flake8: noqa E:721 + """ errorhandler.py @@ -19,12 +21,10 @@ This matter will be improved in a later version. """ import collections.abc -import inspect -import sys import typing from shibokensupport.signature import get_signature -from shibokensupport.signature.mapping import update_mapping, namespace +from shibokensupport.signature.mapping import namespace from textwrap import dedent @@ -77,8 +77,8 @@ def seterror_argument(args, func_name, info): if info == "<": msg = f"{func_name}(): not enough arguments" elif info == "0": - msg = (f"{func_name}(): not enough arguments. " - "Note: keyword arguments are only supported for optional parameters.") + msg = (f"{func_name}(): not enough arguments. " + "Note: keyword arguments are only supported for optional parameters.") elif info == ">": msg = f"{func_name}(): too many arguments" elif info.isalnum(): diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/importhandler.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/importhandler.py index dbde18f18..bae264294 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/importhandler.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/importhandler.py @@ -34,9 +34,10 @@ def finish_import(module): except Exception as e: name = e.__class__.__qualname__ print(72 * "*") - print(f"Error in deprecated.py, ignored:") + print("Error in deprecated.py, ignored:") print(f" {name}: {e}") + """ A note for people who might think this could be written in pure Python: @@ -62,4 +63,3 @@ module, it is *perhaps* possible to solve that. I tried for a day and then gave up, since the solution is anyway not too nice when __import__ must be overridden. """ -#eof diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/layout.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/layout.py index c271be7f7..0e781cbcb 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/layout.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/layout.py @@ -79,6 +79,7 @@ class SignatureLayout(SimpleNamespace): The only allowed values are '{allowed_values}'. """)) + # The following names are used literally in this module. # This way, we avoid the dict hashing problem. signature = SignatureLayout() @@ -115,7 +116,7 @@ def define_nameless_parameter(): P = inspect.Parameter newname = "NamelessParameter" bases = P.__bases__ - body = dict(P.__dict__) # get rid of mappingproxy + body = dict(P.__dict__) # get rid of mappingproxy if "__slots__" in body: # __slots__ would create duplicates for name in body["__slots__"]: @@ -167,12 +168,13 @@ def make_signature_nameless(signature): signature.parameters[key].__class__ = NamelessParameter -_POSITIONAL_ONLY = inspect._POSITIONAL_ONLY -_POSITIONAL_OR_KEYWORD = inspect._POSITIONAL_OR_KEYWORD -_VAR_POSITIONAL = inspect._VAR_POSITIONAL -_KEYWORD_ONLY = inspect._KEYWORD_ONLY -_VAR_KEYWORD = inspect._VAR_KEYWORD -_empty = inspect._empty +_POSITIONAL_ONLY = inspect._POSITIONAL_ONLY # noqa E:201 +_POSITIONAL_OR_KEYWORD = inspect._POSITIONAL_OR_KEYWORD # noqa E:201 +_VAR_POSITIONAL = inspect._VAR_POSITIONAL # noqa E:201 +_KEYWORD_ONLY = inspect._KEYWORD_ONLY # noqa E:201 +_VAR_KEYWORD = inspect._VAR_KEYWORD # noqa E:201 +_empty = inspect._empty # noqa E:201 + def create_signature(props, key): if not props: @@ -183,9 +185,9 @@ def create_signature(props, key): return list(create_signature(elem, key) for elem in props["multi"]) if type(key) is tuple: - sig_kind, modifier = key + _, modifier = key else: - sig_kind, modifier = key, "signature" + _, modifier = key, "signature" layout = globals()[modifier] # lookup of the modifier in this module if not isinstance(layout, SignatureLayout): @@ -234,8 +236,8 @@ def create_signature(props, key): if kind == _VAR_POSITIONAL: kind = _KEYWORD_ONLY sig = inspect.Signature(params, - return_annotation=annotations.get('return', _empty), - __validate_parameters__=False) + return_annotation=annotations.get('return', _empty), + __validate_parameters__=False) # the special case of nameless parameters if not layout.parameter_names: diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/enum_sig.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/enum_sig.py index d07beb881..4988d97a3 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/enum_sig.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/enum_sig.py @@ -14,9 +14,7 @@ by producing a lot of clarity. import inspect import sys import types -import typing from shibokensupport.signature import get_signature as get_sig -from shibokensupport.signature.layout import create_signature """ @@ -106,7 +104,7 @@ class ExactEnumerator(object): return ret if "<" in class_name: # This is happening in QtQuick for some reason: - ## class std::shared_ptr<QQuickItemGrabResult >: + # class std::shared_ptr<QQuickItemGrabResult >: # We simply skip over this class. return ret bases_list = [] @@ -160,8 +158,8 @@ class ExactEnumerator(object): # find out how many functions create a signature sigs = list(_ for _ in functions if get_sig(_[1])) - self.fmt.have_body = bool(subclasses or sigs or properties or enums or init_signature - or signals) + self.fmt.have_body = bool(subclasses or sigs or properties or enums or # noqa W:504 + init_signature or signals) with self.fmt.klass(class_name, class_str): self.fmt.level += 1 @@ -171,7 +169,7 @@ class ExactEnumerator(object): if len(enums): self.section() for enum_name, enum_class_name, value in enums: - with self.fmt.enum(enum_class_name, enum_name,value.value): + with self.fmt.enum(enum_class_name, enum_name, value.value): pass if hasattr(self.fmt, "signal"): # this is an optional feature diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/pyi_generator.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/pyi_generator.py index c44346687..0d36fa10a 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/pyi_generator.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/pyi_generator.py @@ -3,6 +3,8 @@ LICENSE_TEXT = """ # SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only """ +# flake8: noqa E:402 + """ pyi_generator.py @@ -21,7 +23,6 @@ from pathlib import Path from contextlib import contextmanager from textwrap import dedent -from shiboken6 import Shiboken from shibokensupport.signature.lib.enum_sig import HintingEnumerator from shibokensupport.signature.lib.tool import build_brace_pattern @@ -89,6 +90,7 @@ class Formatter(Writer): pattern = fr"\b Union \s* \[ \s* {brace_pat} \s*, \s* NoneType \s* \]" replace = r"Optional[\1]" optional_searcher = re.compile(pattern, flags=re.VERBOSE) + def optional_replacer(source): return optional_searcher.sub(replace, str(source)) self.optional_replacer = optional_replacer @@ -176,6 +178,7 @@ FROM_IMPORTS = [ ("shiboken6", ["Shiboken"]), ] + def filter_from_imports(from_struct, text): """ Build a reduced new `from` structure (nfs) with found entries, only @@ -228,12 +231,10 @@ def generate_pyi(import_name, outpath, options): obj = getattr(top, plainname) if import_name != plainname else top if not getattr(obj, "__file__", None) or Path(obj.__file__).is_dir(): raise ModuleNotFoundError(f"We do not accept a namespace as module `{plainname}`") - module = sys.modules[import_name] outfile = io.StringIO() fmt = Formatter(outfile, options) fmt.print(LICENSE_TEXT.strip()) - need_imports = options._pyside_call and not USE_PEP563 if USE_PEP563: fmt.print("from __future__ import annotations") fmt.print() @@ -298,11 +299,11 @@ def main(): pyi_generator will try to generate an interface "<module>.pyi". """)) parser.add_argument("module", - help="The full path name of an importable module binary (.pyd, .so)") + help="The full path name of an importable module binary (.pyd, .so)") # noqa E:128 parser.add_argument("--quiet", action="store_true", help="Run quietly") parser.add_argument("--check", action="store_true", help="Test the output") parser.add_argument("--outpath", - help="the output directory (default = location of module binary)") + help="the output directory (default = location of module binary)") # noqa E:128 options = parser.parse_args() module = options.module outpath = options.outpath @@ -320,6 +321,7 @@ def main(): options.logger = logger generate_pyi(module, outpath, options=options) + if __name__ == "__main__": main() # eof diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/tool.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/tool.py index a7900e6b2..979dcf4ce 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/tool.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/tool.py @@ -44,8 +44,8 @@ def build_brace_pattern(level, separators): ro, rc = round_ = "()" so, sc = square = "[]" - co, cc = curly = "CD" # we insert "{}", later... - ao, ac = angle = "<>" + co, cc = curly = "CD" # noqa E:201 we insert "{}", later... + ao, ac = angle = "<>" # noqa E:201 q2, bs, q1 = '"', "\\", "'" allpat = round_ + square + curly + angle __ = " " @@ -79,8 +79,8 @@ def build_brace_pattern(level, separators): {indent} )* """) for idx in range(level): - pattern = pattern.format(replacer = repeated if idx < level-1 else no_braces_q, - indent = idx * " ", **locals()) + pattern = pattern.format(replacer=repeated if idx < level - 1 else no_braces_q, + indent=idx * " ", **locals()) return pattern.replace("C", "{").replace("D", "}") diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/loader.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/loader.py index 6349253d1..fb4c9eeca 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/loader.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/loader.py @@ -1,6 +1,9 @@ # Copyright (C) 2022 The Qt Company Ltd. # SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +# flake8: noqa E:402 +# flake8: noqa F:401 + """ loader.py @@ -30,22 +33,27 @@ import types def pyside_type_init(type_key, sig_strings): return parser.pyside_type_init(type_key, sig_strings) + # name used in signature.cpp def create_signature(props, key): return layout.create_signature(props, key) + # name used in signature.cpp def seterror_argument(args, func_name, info): return errorhandler.seterror_argument(args, func_name, info) + # name used in signature.cpp def make_helptext(func): return errorhandler.make_helptext(func) + # name used in signature.cpp def finish_import(module): return importhandler.finish_import(module) + # name used in signature.cpp def feature_import(*args, **kwds): # don't spend a stack level here for speed and compatibility @@ -53,6 +61,7 @@ def feature_import(*args, **kwds): feature_import = feature.feature_import return feature_import(*args, **kwds) + # name used in signature.cpp def feature_imported(*args, **kwds): # don't spend a stack level here for speed and compatibility @@ -107,6 +116,7 @@ def move_into_pyside_package(): put_into_package(PySide6.support.signature.lib, pyi_generator) put_into_package(PySide6.support.signature.lib, tool) + from shibokensupport.signature import mapping from shibokensupport.signature import errorhandler from shibokensupport.signature import layout @@ -119,7 +129,7 @@ from shibokensupport.signature.lib import tool import enum -post_init = lambda:None # default +post_init = lambda: None # noqa E:731 default if "PySide6" in sys.modules: # We publish everything under "PySide6.support", again. @@ -127,7 +137,7 @@ if "PySide6" in sys.modules: # PYSIDE-1502: Make sure that support can be imported. try: import PySide6.support - except ModuleNotFoundError as e: + except ModuleNotFoundError: print("PySide6.support could not be imported. " "This is a serious configuration error.", file=sys.stderr) raise diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/parser.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/parser.py index 1936215dd..794b3f122 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/parser.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/parser.py @@ -3,20 +3,17 @@ import ast import enum -import functools import keyword import os import re import sys -import types import typing import warnings from types import SimpleNamespace from shibokensupport.signature.mapping import (type_map, update_mapping, - namespace, _NotCalled, ResultVariable, ArrayLikeVariable) + namespace, _NotCalled, ResultVariable, ArrayLikeVariable) # noqa E:128 from shibokensupport.signature.lib.tool import build_brace_pattern -from shibokensupport import feature _DEBUG = False LIST_KEYWORDS = False @@ -41,8 +38,9 @@ guesses, we provide an entry in 'type_map' that resolves it. In effect, 'type_map' maps text to real Python objects. """ + def _get_flag_enum_option(): - from shiboken6 import (__version_info__ as ver, + from shiboken6 import (__version_info__ as ver, # noqa F:401 __minimum_python_version__ as pyminver, __maximum_python_version__ as pymaxver) @@ -106,6 +104,7 @@ def dprint(*args, **kw): _cache = {} + def _parse_arglist(argstr): # The following is a split re. The string is broken into pieces which are # between the recognized strings. Because the re has groups, both the @@ -187,7 +186,7 @@ def _handle_instance_fixup(thing): if not match: return thing start, stop = match.start(), match.end() - 1 - pre, func, args = thing[:start], thing[start : stop], thing[stop:] + pre, func, args = thing[:start], thing[start:stop], thing[stop:] if func[0].isupper() or func.startswith("gl") and func[2:3].isupper(): return thing # Now convert this string to snake case. @@ -196,7 +195,7 @@ def _handle_instance_fixup(thing): if char.isupper(): if idx and func[idx - 1].isupper(): # two upper chars are forbidden - return things + return thing snake_func += f"_{char.lower()}" else: snake_func += char @@ -239,12 +238,14 @@ def try_to_guess(thing, valtype): return ret return None + def get_name(thing): if isinstance(thing, type): return getattr(thing, "__qualname__", thing.__name__) else: return thing.__name__ + def _resolve_value(thing, valtype, line): if thing in ("0", "None") and valtype: if valtype.startswith("PySide6.") or valtype.startswith("typing."): @@ -297,7 +298,7 @@ def to_string(thing): dot = "." in str(thing) or m not in (thing.__qualname__, "builtins") name = get_name(thing) ret = m + "." + name if dot else name - assert(eval(ret, globals(), namespace)) + assert (eval(ret, globals(), namespace)) return ret # Note: This captures things from the typing module: return str(thing) @@ -305,8 +306,9 @@ def to_string(thing): matrix_pattern = "PySide6.QtGui.QGenericMatrix" + def handle_matrix(arg): - n, m, typstr = tuple(map(lambda x:x.strip(), arg.split(","))) + n, m, typstr = tuple(map(lambda x: x.strip(), arg.split(","))) assert typstr == "float" result = f"PySide6.QtGui.QMatrix{n}x{m}" return eval(result, globals(), namespace) @@ -334,13 +336,13 @@ def _resolve_type(thing, line, level, var_handler, func_name=None): # Special case: Handle the generic matrices. if contr == matrix_pattern: return handle_matrix(thing) - contr = var_handler(_resolve_type(contr, line, level+1, var_handler)) + contr = var_handler(_resolve_type(contr, line, level + 1, var_handler)) if isinstance(contr, _NotCalled): raise SystemError("Container types must exist:", repr(contr)) contr = to_string(contr) pieces = [] for part in _parse_arglist(thing): - part = var_handler(_resolve_type(part, line, level+1, var_handler)) + part = var_handler(_resolve_type(part, line, level + 1, var_handler)) if isinstance(part, _NotCalled): # fix the tag (i.e. "Missing") by repr part = repr(part) @@ -350,7 +352,7 @@ def _resolve_type(thing, line, level, var_handler, func_name=None): # PYSIDE-1538: Make sure that the eval does not crash. try: return eval(result, globals(), namespace) - except Exception as e: + except Exception: warnings.warn(f"""pyside_type_init:_resolve_type UNRECOGNIZED: {result!r} @@ -429,9 +431,9 @@ def calculate_props(line): props.defaults = defaults props.kwdefaults = {} props.annotations = annotations - props.varnames = varnames = tuple(tup[0] for tup in arglist) + props.varnames = tuple(tup[0] for tup in arglist) funcname = parsed.funcname - shortname = funcname[funcname.rindex(".")+1:] + shortname = funcname[funcname.rindex(".") + 1:] props.name = shortname props.multi = parsed.multi fix_variables(props, line) @@ -477,7 +479,6 @@ def fix_variables(props, line): else: diff -= 1 if retvars: - rvs = [] retvars = list(handle_retvar(rv) if isinstance(rv, ArrayLikeVariable) else rv for rv in retvars) if len(retvars) == 1: |