From 6e3e7b9ca0548430aaa5e2555d6e02c64625fa3f Mon Sep 17 00:00:00 2001 From: Christian Tismer Date: Mon, 2 Nov 2020 12:50:00 +0100 Subject: replace **locals by f-strings where possible This change affects mostly only my own sources which were prepared for the migration to Python 3.6 . Task-number: PYSIDE-904 Change-Id: I0c2cd59f6f625f51f876099c33005ac70ca39db9 Reviewed-by: Cristian Maureira-Fredes --- sources/pyside2/PySide2/__init__.py.in | 5 ++-- sources/pyside2/PySide2/support/deprecated.py | 8 +++--- sources/pyside2/PySide2/support/generate_pyi.py | 31 +++++++++++------------- sources/pyside2/tests/registry/existence_test.py | 8 +++--- sources/pyside2/tests/registry/init_platform.py | 20 +++++++-------- 5 files changed, 34 insertions(+), 38 deletions(-) (limited to 'sources/pyside2') diff --git a/sources/pyside2/PySide2/__init__.py.in b/sources/pyside2/PySide2/__init__.py.in index 89c47ae80..f062c284a 100644 --- a/sources/pyside2/PySide2/__init__.py.in +++ b/sources/pyside2/PySide2/__init__.py.in @@ -68,7 +68,8 @@ def _setupQtDirectories(): # We now use an explicit function instead of touching a signature. _init_pyside_extension() except AttributeError: - print(dedent('''\ + stars = 79 * "*" + print(dedent(f'''\ {stars} PySide2/__init__.py: The `signature` module was not initialized. This libshiboken module was loaded from @@ -77,7 +78,7 @@ def _setupQtDirectories(): Please make sure that this is the real shiboken6 binary and not just a folder. {stars} - ''').format(stars=79*"*", **locals()), file=sys.stderr) + '''), file=sys.stderr) raise if sys.platform == 'win32': diff --git a/sources/pyside2/PySide2/support/deprecated.py b/sources/pyside2/PySide2/support/deprecated.py index 57f33d9e2..af4c18e14 100644 --- a/sources/pyside2/PySide2/support/deprecated.py +++ b/sources/pyside2/PySide2/support/deprecated.py @@ -65,14 +65,14 @@ class PySideDeprecationWarningRemovedInQt6(Warning): def constData(self): cls = self.__class__ name = cls.__qualname__ - warnings.warn(dedent(""" + warnings.warn(dedent(f""" {name}.constData is unpythonic and will be removed in Qt For Python 6.0 . - Please use {name}.data instead.""" - .format(**locals())), PySideDeprecationWarningRemovedInQt6, stacklevel=2) + Please use {name}.data instead."""), PySideDeprecationWarningRemovedInQt6, stacklevel=2) return cls.data(self) -def fix_for_QtGui(QtGui): +# No longer needed but kept for reference. +def _unused_fix_for_QtGui(QtGui): for name, cls in QtGui.__dict__.items(): if name.startswith("QMatrix") and "data" in cls.__dict__: cls.constData = constData diff --git a/sources/pyside2/PySide2/support/generate_pyi.py b/sources/pyside2/PySide2/support/generate_pyi.py index 6cca2ebbe..12ad105b9 100644 --- a/sources/pyside2/PySide2/support/generate_pyi.py +++ b/sources/pyside2/PySide2/support/generate_pyi.py @@ -122,8 +122,7 @@ class Formatter(Writer): # this became _way_ too much. # See also the comment in layout.py . brace_pat = build_brace_pattern(3) - pattern = (r"\b Union \s* \[ \s* {brace_pat} \s*, \s* NoneType \s* \]" - .format(**locals())) + 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): @@ -165,9 +164,9 @@ class Formatter(Writer): self.print() here = self.outfile.tell() if self.have_body: - self.print("{spaces}class {class_str}:".format(**locals())) + self.print(f"{spaces}class {class_str}:") else: - self.print("{spaces}class {class_str}: ...".format(**locals())) + self.print(f"{spaces}class {class_str}: ...") yield @contextmanager @@ -178,7 +177,7 @@ class Formatter(Writer): spaces = indent * self.level if type(signature) == type([]): for sig in signature: - self.print('{spaces}@typing.overload'.format(**locals())) + self.print(f'{spaces}@typing.overload') self._function(func_name, sig, spaces) else: self._function(func_name, signature, spaces) @@ -188,15 +187,15 @@ class Formatter(Writer): def _function(self, func_name, signature, spaces): if "self" not in tuple(signature.parameters.keys()): - self.print('{spaces}@staticmethod'.format(**locals())) + self.print(f'{spaces}@staticmethod') signature = self.optional_replacer(signature) - self.print('{spaces}def {func_name}{signature}: ...'.format(**locals())) + self.print(f'{spaces}def {func_name}{signature}: ...') @contextmanager def enum(self, class_name, enum_name, value): spaces = indent * self.level hexval = hex(value) - self.print("{spaces}{enum_name:25}: {class_name} = ... # {hexval}".format(**locals())) + self.print(f"{spaces}{enum_name:25}: {class_name} = ... # {hexval}") yield @@ -221,8 +220,7 @@ def generate_pyi(import_name, outpath, options): top = __import__(import_name) obj = getattr(top, plainname) if not getattr(obj, "__file__", None) or os.path.isdir(obj.__file__): - raise ModuleNotFoundError("We do not accept a namespace as module " - "{plainname}".format(**locals())) + raise ModuleNotFoundError(f"We do not accept a namespace as module {plainname}") module = sys.modules[import_name] outfile = io.StringIO() @@ -232,12 +230,12 @@ def generate_pyi(import_name, outpath, options): if USE_PEP563: fmt.print("from __future__ import annotations") fmt.print() - fmt.print(dedent('''\ + fmt.print(dedent(f'''\ """ This file contains the exact signatures for all functions in module {import_name}, except for defaults which are replaced by "...". """ - '''.format(**locals()))) + ''')) HintingEnumerator(fmt).module(import_name) fmt.print() fmt.print("# eof") @@ -262,7 +260,7 @@ def generate_pyi(import_name, outpath, options): wr.print() else: wr.print(line) - logger.info("Generated: {outfilepath}".format(**locals())) + logger.info(f"Generated: {outfilepath}") if is_py3 and (options.check or is_ci): # Python 3: We can check the file directly if the syntax is ok. subprocess.check_output([sys.executable, outfilepath]) @@ -292,11 +290,10 @@ def generate_all_pyi(outpath, options): name_list = PySide2.__all__ if options.modules == ["all"] else options.modules errors = ", ".join(set(name_list) - set(PySide2.__all__)) if errors: - raise ImportError("The module(s) '{errors}' do not exist".format(**locals())) + raise ImportError(f"The module(s) '{errors}' do not exist") quirk1, quirk2 = "QtMultimedia", "QtMultimediaWidgets" if name_list == [quirk1]: - logger.debug("Note: We must defer building of {quirk1}.pyi until {quirk2} " - "is available".format(**locals())) + logger.debug(f"Note: We must defer building of {quirk1}.pyi until {quirk2} is available") name_list = [] elif name_list == [quirk2]: name_list = [quirk1, quirk2] @@ -322,6 +319,6 @@ if __name__ == "__main__": outpath = options.outpath if outpath and not os.path.exists(outpath): os.makedirs(outpath) - logger.info("+++ Created path {outpath}".format(**locals())) + logger.info(f"+++ Created path {outpath}") generate_all_pyi(outpath, options=options) # eof diff --git a/sources/pyside2/tests/registry/existence_test.py b/sources/pyside2/tests/registry/existence_test.py index b8a42058d..c8185b140 100644 --- a/sources/pyside2/tests/registry/existence_test.py +++ b/sources/pyside2/tests/registry/existence_test.py @@ -115,8 +115,7 @@ except NameError as e: have_refmodule = False dict_name = "sig_dict" if have_refmodule and not hasattr(sig_exists, dict_name): - print("*** wrong module without '{dict_name}', removed:" - .format(**locals()), shortpath) + print(f"*** wrong module without '{dict_name}', removed: {shortpath}") os.unlink(effectiveRefPath) have_refmodule = False @@ -137,9 +136,8 @@ class TestSignaturesExists(unittest.TestCase): def multi_signature_msg(key, actual, expect): len_act = len(actual) if type(actual) is list else 1 len_exp = len(expect) if type(expect) is list else 1 - return ("multi-signature count mismatch for '{key}'. " - "Actual {len_act} {actual} vs. expected {len_exp} {expect}')" - .format(**locals())) + return (f"multi-signature count mismatch for '{key}'. " + f"Actual {len_act} {actual} vs. expected {len_exp} {expect}") for key, value in sig_exists.sig_dict.items(): name = key.rsplit(".", 1)[-1] diff --git a/sources/pyside2/tests/registry/init_platform.py b/sources/pyside2/tests/registry/init_platform.py index 86548d7e5..e4b8d9cc3 100644 --- a/sources/pyside2/tests/registry/init_platform.py +++ b/sources/pyside2/tests/registry/init_platform.py @@ -170,16 +170,16 @@ class Formatter(object): @contextmanager def module(self, mod_name): - self.print("") - self.print("# Module", mod_name) - self.print("sig_dict.update({") + self.print(f"") + self.print(f"# Module {mod_name}") + self.print(f"sig_dict.update({{") yield - self.print(' }}) if "{mod_name}" in sys.modules else None'.format(**locals())) + self.print(f' }}) if "{mod_name}" in sys.modules else None') @contextmanager def klass(self, class_name, class_str): self.print() - self.print("# class {self.mod_name}.{class_name}:".format(**locals())) + self.print(f"# class {self.mod_name}.{class_name}:") yield @contextmanager @@ -189,15 +189,15 @@ class Formatter(object): self.last_level = self.level class_name = self.class_name if class_name is None: - key = viskey = "{self.mod_name}.{func_name}".format(**locals()) + key = viskey = f"{self.mod_name}.{func_name}" else: - key = viskey = "{self.mod_name}.{class_name}.{func_name}".format(**locals()) + key = viskey = f"{self.mod_name}.{class_name}.{func_name}" if key.endswith("lY"): # Some classes like PySide2.QtGui.QContextMenuEvent have functions # globalX and the same with Y. The gerrit robot thinks that this # is a badly written "globally". Convince it by hiding this word. viskey = viskey[:-1] + '""Y' - self.print(' "{viskey}": {signature},'.format(**locals())) + self.print(f' "{viskey}": {signature},') yield key @@ -223,7 +223,7 @@ def generate_all(): fmt.print("".join(lines[:license_line + 3])) version = sys.version.replace('\n', ' ') build = qt_build() - fmt.print(dedent('''\ + fmt.print(dedent(f'''\ """ This file contains the simplified signatures for all functions in PySide for module '{module}' using @@ -236,7 +236,7 @@ def generate_all(): identical for Python 2 and 3. '__div__' is also removed, since it exists in Python 2, only. """ - '''.format(**locals()))) + ''')) fmt.print("import sys") fmt.print("") fmt.print("sig_dict = {}") -- cgit v1.2.3