diff options
author | Cristian Maureira-Fredes <Cristian.Maureira-Fredes@qt.io> | 2021-01-04 21:03:22 +0100 |
---|---|---|
committer | Qt Cherry-pick Bot <cherrypick_bot@qt-project.org> | 2021-01-06 15:34:36 +0000 |
commit | 5ea0fde59719866f6eb86a4fe4e33d7f389802c5 (patch) | |
tree | db7305af8d7642b4fddf032ece79dc65d2c95ad4 /sources | |
parent | b9a89e1f3c8d0b80cc91bf1d277ead3b7857dabd (diff) |
sources: migration from format() to f-strings
This should be the last patch related the usage of f-strings
from the 'sources' directory.
Change-Id: I0288d720dc4930dee088ca3396a66d1b3ba18f76
Reviewed-by: Friedemann Kleint <Friedemann.Kleint@qt.io>
(cherry picked from commit d9f344fcef6bec04a787f9ea9f4ea94f15eaa26c)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
Diffstat (limited to 'sources')
58 files changed, 146 insertions, 146 deletions
diff --git a/sources/pyside-tools/pyside_tool.py b/sources/pyside-tools/pyside_tool.py index 15db6c4aa..485520f5d 100644 --- a/sources/pyside-tools/pyside_tool.py +++ b/sources/pyside-tools/pyside_tool.py @@ -66,7 +66,8 @@ def qt_tool_wrapper(qt_tool, args): out, err = proc.communicate() if err: msg = err.decode("utf-8") - print("Error: {}\nwhile executing '{}'".format(msg, ' '.join(cmd))) + command = ' '.join(cmd) + print(f"Error: {msg}\nwhile executing '{command}'") sys.exit(proc.returncode) diff --git a/sources/pyside6/PySide6/__init__.py.in b/sources/pyside6/PySide6/__init__.py.in index eb20d7bd3..9b86c1830 100644 --- a/sources/pyside6/PySide6/__init__.py.in +++ b/sources/pyside6/PySide6/__init__.py.in @@ -57,7 +57,7 @@ def _setupQtDirectories(): import shiboken6 except Exception: paths = ', '.join(sys.path) - print('PySide6/__init__.py: Unable to import shiboken6 from {}'.format(paths), + print(f"PySide6/__init__.py: Unable to import shiboken6 from {paths}", file=sys.stderr) raise diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_io_qdir.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_io_qdir.cpp index 11a56ea4c..101ebbb44 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_io_qdir.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_io_qdir.cpp @@ -63,8 +63,8 @@ QDir("images/landscape.png") //! [2] -QDir("Documents/Letters/Applications").dirName() # "Applications" -QDir().dirName() # "." +QDir("Documents/Letters/Applications").dirName() # "Applications" +QDir().dirName() # "." //! [2] @@ -88,8 +88,8 @@ if not dir.cd("tmp"): # "/tmp" print("Cannot find the \"/tmp\" directory") else: file = QFile(dir.filePath("ex1.txt")) # "/tmp/ex1.txt" - if !file.open(QIODevice.ReadWrite): - print("Cannot create the file %s" % (file.name())) + if not file.open(QIODevice.ReadWrite): + print(f"Cannot create the file {file.name()}") //! [5] @@ -115,7 +115,7 @@ s = dir.relativeFilePath("/home/mary/file.txt") # s is "../mary/file.txt" //! [8] -QDir.setSearchPaths("icons", [QDir.homePath() + "/images"]) +QDir.setSearchPaths("icons", [f"{QDir.homePath()}/images"]) QDir.setSearchPaths("docs", [":/embeddedDocuments"]) ... pixmap = QPixmap("icons:undo.png") # will look for undo.png in QDir::homePath() + "/images" diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_io_qfileinfo.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_io_qfileinfo.cpp index c362e2fff..32f9205b9 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_io_qfileinfo.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_io_qfileinfo.cpp @@ -141,8 +141,8 @@ if info.isSymLink(): //! [10] fi = QFileInfo("/tmp/archive.tar.gz") -if fi.permission(QFile.WriteUser | QFile.ReadGroup): +if fi.permission(QFileDevice.WriteUser | QFileDevice.ReadGroup): print("I can change the file; my group can read the file") -if fi.permission(QFile.WriteGroup | QFile.WriteOther): +if fi.permission(QFileDevice.WriteGroup | QFileDevice.WriteOther): print("The group or others can change the file") //! [10] diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_io_qurl.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_io_qurl.cpp index de50b7f8a..7c0d70fee 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_io_qurl.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_io_qurl.cpp @@ -62,7 +62,7 @@ url = QUrl.fromEncoded("http://qtsoftware.com/List%20of%20holidays.xml") //! [2] def checkUrl(url): if !url.isValid(): - print("Invalid URL: %s" % url.toString()) + print(f"Invalid URL: {url.toString()}") return False return True diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_kernel_qobject.py b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_kernel_qobject.py index 7e50f6701..f14573f7a 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_kernel_qobject.py +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_kernel_qobject.py @@ -96,8 +96,7 @@ layout.inherits("QLayoutItem") # returns false //! [5] -print("MyClass.setPrecision(): ({}) invalid precision {}".format(qPrintable(objectName()), - newPrecision)) +print(f"MyClass.setPrecision(): ({qPrintable(objectName())}) invalid precision {newPrecision}" //! [5] diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_tools_qbytearray.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_tools_qbytearray.cpp index e2b6356b9..cd38e2c86 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_tools_qbytearray.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_tools_qbytearray.cpp @@ -86,7 +86,7 @@ x.replace(5, 3, "&") # x == "rock & roll" ba = QByteArray("We must be <b>bold</b>, very <b>bold</b>") j = 0 while (j = ba.indexOf("<b>", j)) != -1: - print("Found <b> tag at index position %d" % j) + print(f"Found <b> tag at index position {j}") ++j //! [4] diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_tools_qdatetime.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_tools_qdatetime.cpp index 2d1b9eb0d..c0b7b3a67 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_tools_qdatetime.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_corelib_tools_qdatetime.cpp @@ -119,7 +119,7 @@ QTime.isValid(22, 5, 62) # returns False //! [10] -t = QTime() +t = QElapsedTimer() t.start() some_lengthy_task() print("Time elapsed: %d ms" % t.elapsed()) diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp index 06062cf79..4ee2391d7 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp @@ -113,7 +113,7 @@ view.render(painter, //! [5] def mousePressEvent(self, event): - print("There are", items(event->pos()).size(), "items at position", mapToScene(event->pos())) + print("There are", items(event->position()).size(), "items at position", mapToScene(event->position())) //! [5] diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_gui_util_qcompleter.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_gui_util_qcompleter.cpp index 370404948..9963b6679 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_gui_util_qcompleter.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_gui_util_qcompleter.cpp @@ -69,6 +69,6 @@ lineEdit.setCompleter(completer) //! [2] i = 0 while completer.setCurrentRow(i): - print("%s is match number %d" % (completer.currentCompletion(), i)) + print(f"{completer.currentCompletion()} is match number {i}") i += 1 //! [2] diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_network_access_qnetworkdiskcache.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_network_access_qnetworkdiskcache.cpp index c8c81ad95..1847e36d4 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_network_access_qnetworkdiskcache.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_network_access_qnetworkdiskcache.cpp @@ -70,5 +70,5 @@ manager.get(request2) @Slot(QNetworkReply) def replyFinished(reply): fromCache = reply.attribute(QNetworkRequest.SourceIsFromCacheAttribute) - print("page from cache? %d" % fromCache) + print(f"page from cache? {fromCache}") //! [2] diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_network_kernel_qhostinfo.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_network_kernel_qhostinfo.cpp index 51128fa6b..e6a1946c2 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_network_kernel_qhostinfo.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_network_kernel_qhostinfo.cpp @@ -70,11 +70,11 @@ QHostInfo.lookupHost("www.kde.org", self.lookedUp) //! [3] def lookedUp(host): if host.error() != QHostInfo.NoError: - print("Lookup failed: %s" % host.errorString()) + print(f"Lookup failed: {host.errorString()}") return for address in host.addresses(): - print("Found address: %s" % address.toString()) + print(f"Found address: {address.toString()}") //! [3] diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_opengl_qgl.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_opengl_qgl.cpp index 761b50970..f7564638e 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_opengl_qgl.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_opengl_qgl.cpp @@ -69,9 +69,9 @@ fmt = QGLFormat() fmt.setOverlay(True) fmt.setStereo(True) myWidget = MyGLWidget(fmt, ...) -if !myWidget.format().stereo(): +if not myWidget.format().stereo(): # ok, goggles off - if !myWidget.format().hasOverlay(): + if not myWidget.format().hasOverlay(): print("Cool hardware required") //! [2] @@ -84,9 +84,9 @@ class MyGLWidget(QGLWidget): def __init__(self, parent): QGLWidget.__init__(self, QGLFormat(QGL.StencilBuffer | QGL.AlphaChannel), parent) - if !format().stencil(): + if not format().stencil(): print("Could not get stencil buffer results will be suboptimal") - if !format().alpha(): + if not format().alpha(): print("Could not get alpha channel results will be suboptimal") ... //! [3] @@ -126,9 +126,9 @@ cx = QGLContext() f = QGLFormat() f.setStereo(True) cx.setFormat(f) -if !cx.create(): +if not cx.create(): exit() # no OpenGL support, or cannot render on the specified paintdevice -if !cx.format().stereo(): +if not cx.format().stereo(): exit() # could not create stereo context //! [7] diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_script_qscriptvalueiterator.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_script_qscriptvalueiterator.cpp index 9d8736e6a..51b0cea20 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_script_qscriptvalueiterator.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_script_qscriptvalueiterator.cpp @@ -54,7 +54,7 @@ object = QScriptValue() it = QScriptValueIterator(object) while it.hasNext(): it.next() - print("%s:%s" % (it.name(), it.value().toString())) + print(f"{it.name()}:{it.value().toString()}") //! [0] @@ -74,5 +74,5 @@ while it.hasNext(): it.next() if it.flags() & QScriptValue::SkipInEnumeration: continue - print("found enumerated property: %s" % it.name()) + print(f"found enumerated property: {it.name()}") //! [2] diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_xml_dom_qdom.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_xml_dom_qdom.cpp index 54d932ebd..de173fc7c 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_xml_dom_qdom.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/code/src_xml_dom_qdom.cpp @@ -74,7 +74,7 @@ n = d.firstChild() while !n.isNull(): if n.isElement(): e = n.toElement() - print("Element name: %s" % e.tagName()) + print(f"Element name: {e.tagName()}") break n = n.nextSibling() //! [1] diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/qdir-listfiles/main.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/qdir-listfiles/main.cpp index 204fac414..3e94053df 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/qdir-listfiles/main.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/qdir-listfiles/main.cpp @@ -59,6 +59,6 @@ directory.setFilter(QDir.Files | QDir.Hidden | QDir.NoSymLinks) directory.setSorting(QDir.Size | QDir.Reversed) for entry in directory.entryInfoList(): - print("%s %s" % (entry.size(), entry.fileName())) + print(f"{entry.size()} {entry.fileName()}") //! [0] diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/qdir-namefilters/main.cpp b/sources/pyside6/doc/codesnippets/doc/src/snippets/qdir-namefilters/main.cpp index 7f6c4b083..5577ffb14 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/qdir-namefilters/main.cpp +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/qdir-namefilters/main.cpp @@ -64,5 +64,5 @@ def main(): print(" Bytes Filename") for fileInfo in lst: - print('%d %s' % (fileInfo.size(), fileInfo.fileName())) + print("{fileInfo.size()} {fileInfo.fileName()}") diff --git a/sources/pyside6/doc/codesnippets/doc/src/snippets/sqldatabase/sqldatabase.py b/sources/pyside6/doc/codesnippets/doc/src/snippets/sqldatabase/sqldatabase.py index 747f7b983..1156e6541 100644 --- a/sources/pyside6/doc/codesnippets/doc/src/snippets/sqldatabase/sqldatabase.py +++ b/sources/pyside6/doc/codesnippets/doc/src/snippets/sqldatabase/sqldatabase.py @@ -171,7 +171,7 @@ def QSqlQuery_snippets(): i = query.boundValues() while i.hasNext(): i.next() - print(i.key(), ": ", i.value()) + print(f"{i.key()}:{i.value()}") //! [14] # examine with positional binding @@ -381,7 +381,7 @@ def sql_intro_snippets(): for i in range(model.rowCount()): name = model.record(i).value("name") salary = model.record(i).value("salary") - print("%s: %d" % (name, salary)) + print(f"{name}: {salary}") //! [41] diff --git a/sources/pyside6/doc/codesnippets/examples/dialogs/standarddialogs/dialog.cpp b/sources/pyside6/doc/codesnippets/examples/dialogs/standarddialogs/dialog.cpp index db11e22f8..3132bec55 100644 --- a/sources/pyside6/doc/codesnippets/examples/dialogs/standarddialogs/dialog.cpp +++ b/sources/pyside6/doc/codesnippets/examples/dialogs/standarddialogs/dialog.cpp @@ -52,14 +52,14 @@ i, ok = QInputDialog().getInteger(self, "QInputDialog().getInteger()", "Percentage:", 25, 0, 100, 1) if ok: - self.integerLabel.setText("{}%".format(i)) + self.integerLabel.setText(f"{i}%") //! [0] //! [1] d, ok = QInputDialog().getDouble(self, "QInputDialog().getDouble()", "Amount:", 37.56, -10000, 10000, 2) if ok: - doubleLabel.setText("${}".format()) + doubleLabel.setText(f"${d}") //! [1] //! [2] diff --git a/sources/pyside6/doc/codesnippets/examples/mainwindows/application/mainwindow.py b/sources/pyside6/doc/codesnippets/examples/mainwindows/application/mainwindow.py index f9a93cfc8..fb58f05a8 100644 --- a/sources/pyside6/doc/codesnippets/examples/mainwindows/application/mainwindow.py +++ b/sources/pyside6/doc/codesnippets/examples/mainwindows/application/mainwindow.py @@ -281,7 +281,7 @@ def writeSettings(self): //! [40] def maybeSave(self): //! [40] //! [41] - if textEdit.document()->isModified(): + if textEdit.document().isModified(): ret = QMessageBox.warning(self, tr("Application"), tr("The document has been modified.\n" "Do you want to save your changes?"), @@ -299,7 +299,7 @@ def loadFile(self, fileName): file = QFile(fileName) if !file.open(QFile.ReadOnly | QFile.Text): QMessageBox.warning(self, tr("Application"), tr("Cannot read file " - "{}:\n{}.".format(fileName, file.errorString()))) + f"{fileName}:\n{file.errorString()}.")) return in = QTextStream(file) diff --git a/sources/pyside6/doc/codesnippets/examples/mainwindows/mdi/mainwindow.py b/sources/pyside6/doc/codesnippets/examples/mainwindows/mdi/mainwindow.py index 9d0572d9a..984210189 100644 --- a/sources/pyside6/doc/codesnippets/examples/mainwindows/mdi/mainwindow.py +++ b/sources/pyside6/doc/codesnippets/examples/mainwindows/mdi/mainwindow.py @@ -163,10 +163,11 @@ class QMdiSubWindow(QMainWindow): child = windows.at(i).widget() text = "" + child_file = child.userFriendlyCurrentFile() if i < 9: - text = "{} {}".format(i + 1, child.userFriendlyCurrentFile()) + text = f"&{i + 1} {child_file}" else: - text = "{} {}".format(i + 1, child.userFriendlyCurrentFile()) + text = f"{i + 1} {child_file}" action = windowMenu.addAction(text) action.setCheckable(True) diff --git a/sources/pyside6/doc/inheritance_diagram.py b/sources/pyside6/doc/inheritance_diagram.py index e8dc69532..e8bb93f13 100644 --- a/sources/pyside6/doc/inheritance_diagram.py +++ b/sources/pyside6/doc/inheritance_diagram.py @@ -110,11 +110,11 @@ class InheritanceGraph(object): """ todoc = importClassOrModule(name) if not todoc and currmodule is not None: - todoc = importClassOrModule(currmodule + '.' + name) + todoc = importClassOrModule(f"{currmodule}.{name}") if not todoc: - moduleStr = '(module {})'.format(currmodule) if currmodule else '' - raise InheritanceException('Could not import class {} specified for ' - 'inheritance diagram {}.'.format(name, moduleStr)) + moduleStr = f'(module {currmodule})' if currmodule else '' + raise InheritanceException(f'Could not import class {name} specified for ' + f'inheritance diagram {moduleStr}.') if inspect.isclass(todoc): return [todoc] elif inspect.ismodule(todoc): @@ -123,8 +123,8 @@ class InheritanceGraph(object): if inspect.isclass(cls) and cls.__module__ == todoc.__name__: classes.append(cls) return classes - raise InheritanceException('%r specified for inheritance diagram is ' - 'not a class or module' % name) + raise InheritanceException(f'{name} specified for inheritance diagram is ' + 'not a class or module') def _import_classes(self, class_names, currmodule): """Import a list of classes.""" @@ -176,7 +176,7 @@ class InheritanceGraph(object): if module == '__builtin__': fullname = cls.__name__ else: - fullname = '%s.%s' % (module, cls.__qualname__) + fullname = f"{module}.{cls.__qualname__)}" if parts == 0: return fullname name_parts = fullname.split('.') @@ -210,7 +210,7 @@ class InheritanceGraph(object): return ','.join(['%s=%s' % x for x in attrs.items()]) def _format_graph_attrs(self, attrs): - return ''.join(['%s=%s;\n' % x for x in attrs.items()]) + return ''.join([f"{x[0]}={x[1]};\n" for x in attrs.items()]) def generate_dot(self, name, urls={}, env=None, graph_attrs={}, node_attrs={}, edge_attrs={}): diff --git a/sources/pyside6/doc/qtattributionsscannertorst.py b/sources/pyside6/doc/qtattributionsscannertorst.py index ff966b4cf..59f11ca9c 100644 --- a/sources/pyside6/doc/qtattributionsscannertorst.py +++ b/sources/pyside6/doc/qtattributionsscannertorst.py @@ -46,7 +46,7 @@ import os, json, subprocess, sys, warnings def indent(lines, indent): result = '' for l in lines: - result += "{}{}\n".format(indent, l) + result = f"{result}{indent}{l}\n" return result rstHeader="""Licenses Used in Qt for Python @@ -76,13 +76,13 @@ code licensed under third-party opensource licenses: """ def rstHeadline(title): - return '{}\n{}\n'.format(title, '-' * len(title)) + return f"{title}\n{'-' * len(title)}\n" def rstUrl(title, url): - return '`{} <{}>`_'.format(title, url) + return f"`{title} <{url}>`_" def rstLiteralBlock(lines): - return '::\n\n' + indent(lines, ' ') + '\n\n' + return f"::\n\n{indent(lines, ' ')}\n\n" def rstLiteralBlockFromText(text): return rstLiteralBlock(text.strip().split('\n')) @@ -94,21 +94,19 @@ def readFile(fileName): def runScanner(directory, targetFileName): # qtattributionsscanner recursively searches for qt_attribution.json files # and outputs them in JSON with the paths of the 'LicenseFile' made absolute - command = 'qtattributionsscanner --output-format json {}'.format(directory) + command = f'qtattributionsscanner --output-format json {directory}' jsonS = subprocess.check_output(command, shell=True) if not jsonS: - raise RuntimeError('{} failed to produce output.'.format(command)) + raise RuntimeError(f'{command} failed to produce output.') with open(targetFileName, 'w') as targetFile: targetFile.write(rstHeader) for entry in json.loads(jsonS.decode('utf-8')): - content = '{}\n{}\n{}\n\n'.format(rstHeadline(entry['Name']), - entry['Description'], entry['QtUsage']) + content = f"{entry['Name']}\n{entry['Description']}\n{entry['QtUsage']}\n\n" url = entry['Homepage'] version = entry['Version'] if url and version: - content += '{}, upstream version: {}\n\n'.format( - rstUrl('Project Homepage', url), version) + content = f"{content}{rstUrl('Project Homepage', url)}, upstream version: {version}\n\n" copyright = entry['Copyright'] if copyright: content += rstLiteralBlockFromText(copyright) @@ -118,8 +116,7 @@ def runScanner(directory, targetFileName): if os.path.isfile(licenseFile): content += rstLiteralBlock(readFile(licenseFile)) else: - warnings.warn('"{}" is not a file'.format(licenseFile), - RuntimeWarning) + warnings.warn(f'"{licenseFile}" is not a file', RuntimeWarning) targetFile.write(content) if len(sys.argv) < 3: diff --git a/sources/pyside6/doc/tutorials/basictutorial/dialog.rst b/sources/pyside6/doc/tutorials/basictutorial/dialog.rst index 8246ddd7a..04f6ffa5d 100644 --- a/sources/pyside6/doc/tutorials/basictutorial/dialog.rst +++ b/sources/pyside6/doc/tutorials/basictutorial/dialog.rst @@ -88,7 +88,7 @@ the Form, so you have to add it after the `init()` function: # Greets the user def greetings(self): - print("Hello {}".format(self.edit.text())) + print(f"Hello {self.edit.text()}") Our function just prints the contents of the `QLineEdit` to the python console. We have access to the text by means of the @@ -133,7 +133,7 @@ Here is the complete code for this tutorial: # Greets the user def greetings(self): - print("Hello %s" % self.edit.text()) + print(f"Hello {self.edit.text()}") if __name__ == '__main__': # Create the Qt Application diff --git a/sources/pyside6/doc/tutorials/basictutorial/uifiles.rst b/sources/pyside6/doc/tutorials/basictutorial/uifiles.rst index 50bb2514c..b8a67b51f 100644 --- a/sources/pyside6/doc/tutorials/basictutorial/uifiles.rst +++ b/sources/pyside6/doc/tutorials/basictutorial/uifiles.rst @@ -167,7 +167,7 @@ The complete code of this example looks like this: ui_file_name = "mainwindow.ui" ui_file = QFile(ui_file_name) if not ui_file.open(QIODevice.ReadOnly): - print("Cannot open {}: {}".format(ui_file_name, ui_file.errorString())) + print(f"Cannot open {ui_file_name}: {ui_file.errorString()}") sys.exit(-1) loader = QUiLoader() window = loader.load(ui_file) diff --git a/sources/pyside6/doc/tutorials/basictutorial/widgetstyling.py b/sources/pyside6/doc/tutorials/basictutorial/widgetstyling.py index 94e44c5c5..69caf177f 100644 --- a/sources/pyside6/doc/tutorials/basictutorial/widgetstyling.py +++ b/sources/pyside6/doc/tutorials/basictutorial/widgetstyling.py @@ -62,7 +62,7 @@ class Widget(QWidget): menu_widget = QListWidget() for i in range(10): - item = QListWidgetItem("Item {}".format(i)) + item = QListWidgetItem(f"Item {i}") item.setTextAlignment(Qt.AlignCenter) menu_widget.addItem(item) diff --git a/sources/pyside6/doc/tutorials/datavisualize/datavisualize4/table_model.py b/sources/pyside6/doc/tutorials/datavisualize/datavisualize4/table_model.py index d9c50acb3..3ccf8162b 100644 --- a/sources/pyside6/doc/tutorials/datavisualize/datavisualize4/table_model.py +++ b/sources/pyside6/doc/tutorials/datavisualize/datavisualize4/table_model.py @@ -66,7 +66,7 @@ class CustomTableModel(QAbstractTableModel): if orientation == Qt.Horizontal: return ("Date", "Magnitude")[section] else: - return "{}".format(section) + return f"{section}" def data(self, index, role=Qt.DisplayRole): column = index.column() @@ -74,11 +74,11 @@ class CustomTableModel(QAbstractTableModel): if role == Qt.DisplayRole: if column == 0: - raw_date = self.input_dates[row] - date = "{}".format(raw_date.toPython()) + date = self.input_dates[row].toPython() return date[:-3] elif column == 1: - return "{:.2f}".format(self.input_magnitudes[row]) + magnitude = self.input_magnitudes[row] + return f"{magnitude:.2f}" elif role == Qt.BackgroundRole: return QColor(Qt.white) elif role == Qt.TextAlignmentRole: diff --git a/sources/pyside6/doc/tutorials/datavisualize/datavisualize5/table_model.py b/sources/pyside6/doc/tutorials/datavisualize/datavisualize5/table_model.py index d9c50acb3..3ccf8162b 100644 --- a/sources/pyside6/doc/tutorials/datavisualize/datavisualize5/table_model.py +++ b/sources/pyside6/doc/tutorials/datavisualize/datavisualize5/table_model.py @@ -66,7 +66,7 @@ class CustomTableModel(QAbstractTableModel): if orientation == Qt.Horizontal: return ("Date", "Magnitude")[section] else: - return "{}".format(section) + return f"{section}" def data(self, index, role=Qt.DisplayRole): column = index.column() @@ -74,11 +74,11 @@ class CustomTableModel(QAbstractTableModel): if role == Qt.DisplayRole: if column == 0: - raw_date = self.input_dates[row] - date = "{}".format(raw_date.toPython()) + date = self.input_dates[row].toPython() return date[:-3] elif column == 1: - return "{:.2f}".format(self.input_magnitudes[row]) + magnitude = self.input_magnitudes[row] + return f"{magnitude:.2f}" elif role == Qt.BackgroundRole: return QColor(Qt.white) elif role == Qt.TextAlignmentRole: diff --git a/sources/pyside6/doc/tutorials/datavisualize/datavisualize6/main_widget.py b/sources/pyside6/doc/tutorials/datavisualize/datavisualize6/main_widget.py index 2934a361f..d8132265d 100644 --- a/sources/pyside6/doc/tutorials/datavisualize/datavisualize6/main_widget.py +++ b/sources/pyside6/doc/tutorials/datavisualize/datavisualize6/main_widget.py @@ -127,5 +127,6 @@ class Widget(QWidget): self.series.attachAxis(self.axis_y) # Getting the color from the QChart to use it on the QTableView - self.model.color = "{}".format(self.series.pen().color().name()) + color_name = self.series.pen().color().name() + self.model.color = f"{color_name}" diff --git a/sources/pyside6/doc/tutorials/datavisualize/datavisualize6/table_model.py b/sources/pyside6/doc/tutorials/datavisualize/datavisualize6/table_model.py index abe3bf2ae..f46d5d402 100644 --- a/sources/pyside6/doc/tutorials/datavisualize/datavisualize6/table_model.py +++ b/sources/pyside6/doc/tutorials/datavisualize/datavisualize6/table_model.py @@ -67,7 +67,7 @@ class CustomTableModel(QAbstractTableModel): if orientation == Qt.Horizontal: return ("Date", "Magnitude")[section] else: - return "{}".format(section) + return f"{section}" def data(self, index, role=Qt.DisplayRole): column = index.column() @@ -75,11 +75,11 @@ class CustomTableModel(QAbstractTableModel): if role == Qt.DisplayRole: if column == 0: - raw_date = self.input_dates[row] - date = "{}".format(raw_date.toPython()) + date = self.input_dates[row].toPython() return date[:-3] elif column == 1: - return "{:.2f}".format(self.input_magnitudes[row]) + magnitude = self.input_magnitudes[row] + return f"{magnitude:.2f}" elif role == Qt.BackgroundRole: return (QColor(Qt.white), QColor(self.color))[column] elif role == Qt.TextAlignmentRole: diff --git a/sources/pyside6/doc/tutorials/expenses/main.py b/sources/pyside6/doc/tutorials/expenses/main.py index 2eec5defb..4dcaedb50 100644 --- a/sources/pyside6/doc/tutorials/expenses/main.py +++ b/sources/pyside6/doc/tutorials/expenses/main.py @@ -118,7 +118,7 @@ class Widget(QWidget): self.table.insertRow(self.items) description_item = QTableWidgetItem(des) - price_item = QTableWidgetItem("{:.2f}".format(float(price))) + price_item = QTableWidgetItem(f"{float(price):.2f}") price_item.setTextAlignment(Qt.AlignRight) self.table.setItem(self.items, 0, description_item) @@ -158,7 +158,7 @@ class Widget(QWidget): data = self._data if not data else data for desc, price in data.items(): description_item = QTableWidgetItem(desc) - price_item = QTableWidgetItem("{:.2f}".format(price)) + price_item = QTableWidgetItem(f"{price:.2f}") price_item.setTextAlignment(Qt.AlignRight) self.table.insertRow(self.items) self.table.setItem(self.items, 0, description_item) diff --git a/sources/pyside6/doc/tutorials/expenses/main_snake_prop.py b/sources/pyside6/doc/tutorials/expenses/main_snake_prop.py index cea2f5767..92ad2b92c 100644 --- a/sources/pyside6/doc/tutorials/expenses/main_snake_prop.py +++ b/sources/pyside6/doc/tutorials/expenses/main_snake_prop.py @@ -121,7 +121,7 @@ class Widget(QWidget): self.table.insert_row(self.items) description_item = QTableWidgetItem(des) - price_item = QTableWidgetItem("{:.2f}".format(float(price))) + price_item = QTableWidgetItem(f"{float(price):.2f}") price_item.text_alignment = Qt.AlignRight self.table.set_item(self.items, 0, description_item) @@ -161,7 +161,7 @@ class Widget(QWidget): data = self._data if not data else data for desc, price in data.items(): description_item = QTableWidgetItem(desc) - price_item = QTableWidgetItem("{:.2f}".format(price)) + price_item = QTableWidgetItem(f"{price:.2f}") price_item.text_alignment = Qt.AlignRight self.table.insert_row(self.items) self.table.set_item(self.items, 0, description_item) diff --git a/sources/pyside6/doc/tutorials/expenses/steps/10-expenses.py b/sources/pyside6/doc/tutorials/expenses/steps/10-expenses.py index 2329805a7..7e33f6acb 100644 --- a/sources/pyside6/doc/tutorials/expenses/steps/10-expenses.py +++ b/sources/pyside6/doc/tutorials/expenses/steps/10-expenses.py @@ -118,7 +118,7 @@ class Widget(QWidget): self.table.insertRow(self.items) description_item = QTableWidgetItem(des) - price_item = QTableWidgetItem("{:.2f}".format(float(price))) + price_item = QTableWidgetItem(f"{float(price):.2f}") price_item.setTextAlignment(Qt.AlignRight) self.table.setItem(self.items, 0, description_item) @@ -158,7 +158,7 @@ class Widget(QWidget): data = self._data if not data else data for desc, price in data.items(): description_item = QTableWidgetItem(desc) - price_item = QTableWidgetItem("{:.2f}".format(price)) + price_item = QTableWidgetItem(f"{price:.2f}") price_item.setTextAlignment(Qt.AlignRight) self.table.insertRow(self.items) self.table.setItem(self.items, 0, description_item) diff --git a/sources/pyside6/doc/tutorials/qmlsqlintegration/main.py b/sources/pyside6/doc/tutorials/qmlsqlintegration/main.py index 50a3d43fe..03050ff32 100644 --- a/sources/pyside6/doc/tutorials/qmlsqlintegration/main.py +++ b/sources/pyside6/doc/tutorials/qmlsqlintegration/main.py @@ -62,7 +62,8 @@ def connectToDatabase(): logger.error("Failed to create writable directory") # Ensure that we have a writable location on all devices. - filename = "{}/chat-database.sqlite3".format(write_dir.absolutePath()) + abs_path = write_dir.absolutePath() + filename = f"{abs_path}/chat-database.sqlite3" # When using the SQLite driver, open() will create the SQLite # database if it doesn't exist. diff --git a/sources/pyside6/doc/tutorials/qmlsqlintegration/sqlDialog.py b/sources/pyside6/doc/tutorials/qmlsqlintegration/sqlDialog.py index a9745051b..2b62c578b 100644 --- a/sources/pyside6/doc/tutorials/qmlsqlintegration/sqlDialog.py +++ b/sources/pyside6/doc/tutorials/qmlsqlintegration/sqlDialog.py @@ -96,9 +96,8 @@ class SqlConversationModel(QSqlTableModel): self.recipient = recipient - filter_str = ( - "(recipient = '{}' AND author = 'Me') OR " "(recipient = 'Me' AND author='{}')" - ).format(self.recipient) + filter_str = (f"(recipient = '{self.recipient}' AND author = 'Me') OR " + f"(recipient = 'Me' AND author='{self.recipient}')") self.setFilter(filter_str) self.select() @@ -136,10 +135,10 @@ class SqlConversationModel(QSqlTableModel): new_record.setValue("timestamp", str(timestamp)) new_record.setValue("message", message) - logging.debug('Message: "{}" \n Received by: "{}"'.format(message, recipient)) + logging.debug(f'Message: "{message}" \n Received by: "{recipient}"') if not self.insertRecord(self.rowCount(), new_record): - logging.error("Failed to send message: {}".format(self.lastError().text())) + logging.error("Failed to send message: {self.lastError().text()}") return self.submitAll() diff --git a/sources/pyside6/pyside_version.py b/sources/pyside6/pyside_version.py index 88b65353f..b5ebfa59c 100644 --- a/sources/pyside6/pyside_version.py +++ b/sources/pyside6/pyside_version.py @@ -51,5 +51,5 @@ pre_release_version = "1" if __name__ == '__main__': # Used by CMake. - print('{0};{1};{2};{3};{4}'.format(major_version, minor_version, patch_version, - release_version_type, pre_release_version)) + print(f'{major_version};{minor_version};{patch_version};' + f'{release_version_type};{pre_release_version}') diff --git a/sources/pyside6/tests/QtCore/bug_PYSIDE-164.py b/sources/pyside6/tests/QtCore/bug_PYSIDE-164.py index a67d2fc75..29097c6d2 100644 --- a/sources/pyside6/tests/QtCore/bug_PYSIDE-164.py +++ b/sources/pyside6/tests/QtCore/bug_PYSIDE-164.py @@ -51,7 +51,7 @@ class Receiver(QObject): self.eventloop = eventloop def receive(self, number): - print("Received number: %d" % number) + print(f"Received number: {number}") self.eventloop.exit(0) diff --git a/sources/pyside6/tests/QtCore/multiple_feature_test.py b/sources/pyside6/tests/QtCore/multiple_feature_test.py index 83e96a2ee..267b4a6cd 100644 --- a/sources/pyside6/tests/QtCore/multiple_feature_test.py +++ b/sources/pyside6/tests/QtCore/multiple_feature_test.py @@ -100,19 +100,20 @@ class FeaturesTest(unittest.TestCase): for bit in range(2, 8): # We are cheating here, since the functions are in the globals. - eval(compile(dedent(""" + bit_pow = 1 << bit + eval(compile(dedent(f""" - def tst_bit{0}(flag, self, bits): + def tst_bit{bit}(flag, self, bits): if flag == 0: with self.assertRaises(AttributeError): - QtCore.QCborArray.fake_feature_{1:02x} + QtCore.QCborArray.fake_feature_{bit_pow:02x} with self.assertRaises(KeyError): - QtCore.QCborArray.__dict__["fake_feature_{1:02x}"] + QtCore.QCborArray.__dict__["fake_feature_{bit_pow:02x}"] else: - QtCore.QCborArray.fake_feature_{1:02x} - QtCore.QCborArray.__dict__["fake_feature_{1:02x}"] + QtCore.QCborArray.fake_feature_{bit_pow:02x} + QtCore.QCborArray.__dict__["fake_feature_{bit_pow:02x}"] - """).format(bit, 1 << bit), "<string>", "exec"), globals(), edict) + """), "<string>", "exec"), globals(), edict) globals().update(edict) feature_list = __feature__._really_all_feature_names func_list = [tst_bit0, tst_bit1, tst_bit2, tst_bit3, @@ -120,14 +121,14 @@ class FeaturesTest(unittest.TestCase): for idx in range(0x100): __feature__.set_selection(0) - config = "feature_{:02x}".format(idx) + config = f"feature_{idx:02x}" print() - print("--- Feature Test Config `{}` ---".format(config)) + print(f"--- Feature Test Config `{config}` ---") print("Imports:") for bit in range(8): if idx & 1 << bit: feature = feature_list[bit] - text = "from __feature__ import {}".format(feature) + text = f"from __feature__ import {feature}" print(text) eval(compile(text, "<string>", "exec"), globals(), edict) for bit in range(8): diff --git a/sources/pyside6/tests/QtCore/qlockfile_test.py b/sources/pyside6/tests/QtCore/qlockfile_test.py index dcd9ecc44..52c517465 100644 --- a/sources/pyside6/tests/QtCore/qlockfile_test.py +++ b/sources/pyside6/tests/QtCore/qlockfile_test.py @@ -45,7 +45,7 @@ class TestQMessageAuthenticationCode (unittest.TestCase): def setUp(self): pid = QCoreApplication.applicationPid() - self._fileName = "{}/pqlockfiletest{}.tmp".format(QDir.tempPath(), pid) + self._fileName = f"{QDir.tempPath()}/pqlockfiletest{pid}.tmp" def tearDown(self): if (os.path.exists(self._fileName)): diff --git a/sources/pyside6/tests/QtCore/qoperatingsystemversion_test.py b/sources/pyside6/tests/QtCore/qoperatingsystemversion_test.py index b9ed2d870..0e27e68d3 100644 --- a/sources/pyside6/tests/QtCore/qoperatingsystemversion_test.py +++ b/sources/pyside6/tests/QtCore/qoperatingsystemversion_test.py @@ -39,8 +39,7 @@ from PySide6.QtCore import QOperatingSystemVersion class TestQOperatingSystemVersion(unittest.TestCase): def test(self): ov = QOperatingSystemVersion.current() - name = "{} v{}.{}.{}".format(ov.name(), ov.majorVersion(), - ov.minorVersion(), ov.microVersion()) + name = f"{ov.name()} v{ov.majorVersion()}.{ov.minorVersion()}.{ov.microVersion()}" print(name) if __name__ == '__main__': diff --git a/sources/pyside6/tests/QtPositioning/positioning.py b/sources/pyside6/tests/QtPositioning/positioning.py index 7edcefcd8..70480e61d 100644 --- a/sources/pyside6/tests/QtPositioning/positioning.py +++ b/sources/pyside6/tests/QtPositioning/positioning.py @@ -44,7 +44,7 @@ class QPositioningTestCase(unittest.TestCase): source = QGeoPositionInfoSource.createDefaultSource(None) self.assertTrue(source is not None) name = source.sourceName() - print('QtPositioning source: {}'.format(name)) + print(f"QtPositioning source: {name}") self.assertTrue(name) if __name__ == "__main__": diff --git a/sources/pyside6/tests/QtSvgWidgets/qsvgwidget_test.py b/sources/pyside6/tests/QtSvgWidgets/qsvgwidget_test.py index b4b5267e9..3d15e948c 100644 --- a/sources/pyside6/tests/QtSvgWidgets/qsvgwidget_test.py +++ b/sources/pyside6/tests/QtSvgWidgets/qsvgwidget_test.py @@ -43,8 +43,8 @@ from PySide6.QtSvgWidgets import QSvgWidget class QSvgWidgetTest(unittest.TestCase): def testLoad(self): - dir = os.path.dirname(__file__) - tigerPath = QDir.cleanPath("{}/../QtSvg/tiger.svg".format(dir)) + directory = os.path.dirname(__file__) + tigerPath = QDir.cleanPath(f"{directory}/../QtSvg/tiger.svg") self.assertTrue(QFileInfo.exists(tigerPath)) app = QApplication([]) diff --git a/sources/pyside6/tests/init_paths.py b/sources/pyside6/tests/init_paths.py index 0230ca99d..64b4f8791 100644 --- a/sources/pyside6/tests/init_paths.py +++ b/sources/pyside6/tests/init_paths.py @@ -54,7 +54,7 @@ def _get_qt_dir(): break if not result: raise ValueError('Unable to locate Qt. Please set the environment variable QT_DIR') - print('Qt as determined by path search: {}'.format(result), file=sys.stderr) + print(f"Qt as determined by path search: {result}", file=sys.stderr) return result diff --git a/sources/pyside6/tests/pysidetest/all_modules_load_test.py b/sources/pyside6/tests/pysidetest/all_modules_load_test.py index 85807b825..08a78aa40 100644 --- a/sources/pyside6/tests/pysidetest/all_modules_load_test.py +++ b/sources/pyside6/tests/pysidetest/all_modules_load_test.py @@ -45,7 +45,7 @@ class AllModulesImportTest(unittest.TestCase): def testAllModulesCanImport(self): # would also work: exec("from PySide6 import *") for name in PySide6.__all__: - exec("import PySide6.{}".format(name)) + exec(f"import PySide6.{name}") if __name__ == '__main__': unittest.main() diff --git a/sources/pyside6/tests/pysidetest/new_inherited_functions_test.py b/sources/pyside6/tests/pysidetest/new_inherited_functions_test.py index 5e342182a..7a8e03fe8 100644 --- a/sources/pyside6/tests/pysidetest/new_inherited_functions_test.py +++ b/sources/pyside6/tests/pysidetest/new_inherited_functions_test.py @@ -122,7 +122,7 @@ class MainTest(unittest.TestCase): """ for app in "QtWidgets.QApplication", "QtGui.QGuiApplication", "QtCore.QCoreApplication": try: - exec("qApp = PySide6.{0}([]) or PySide6.{0}.instance()".format(app)) + exec(f"qApp = PySide6.{app}([]) or PySide6.{app}.instance()") break except AttributeError: continue diff --git a/sources/pyside6/tests/registry/init_platform.py b/sources/pyside6/tests/registry/init_platform.py index bceb80190..90a7a21a8 100644 --- a/sources/pyside6/tests/registry/init_platform.py +++ b/sources/pyside6/tests/registry/init_platform.py @@ -85,7 +85,7 @@ elif os.path.exists(history_dir): try: all_build_dir = f_contents_split[0] except IndexError: - print("Error: can't find the build dir in the given file '{}'".format(fpath)) + print(f"Error: can't find the build dir in the given file '{fpath}'") sys.exit(1) else: print(dedent(""" @@ -244,8 +244,7 @@ def generate_all(): def __main__(): - print("+++ generating {}. You should probably check this file in." - .format(get_refpath())) + print(f"+++ generating {get_refpath()}. You should probably check this file in.") generate_all() diff --git a/sources/pyside6/tests/registry/util.py b/sources/pyside6/tests/registry/util.py index cbbec2383..dba4b5c0a 100644 --- a/sources/pyside6/tests/registry/util.py +++ b/sources/pyside6/tests/registry/util.py @@ -147,8 +147,8 @@ def qt_version(): # Format a registry file name for version. def _registry_filename(version, use_ci_module): - name = "exists_{}_{}_{}_{}{}.py".format(platform_name, - version[0], version[1], version[2], "_ci" if use_ci_module else "") + ext_ci = "_ci" if use_ci_module else "" + name = f"exists_{platform_name}_{version[0]}_{version[1]}_{version[2]}{ext_ci}.py" return os.path.join(os.path.dirname(__file__), name) # Return the expected registry file name. diff --git a/sources/pyside6/tests/util/processtimer.py b/sources/pyside6/tests/util/processtimer.py index 74fe93648..067f1d29c 100644 --- a/sources/pyside6/tests/util/processtimer.py +++ b/sources/pyside6/tests/util/processtimer.py @@ -67,11 +67,11 @@ if __name__ == "__main__": try: t.waitfor() except TimeoutException: - print("timeout - PID: %d" % (t.proc.pid)) + print(f"timeout - PID: {t.proc.pid}") #TODO: detect SO and kill accordingly #Linux os.kill(t.proc.pid, 9) #Windows (not tested) #subprocess.Popen("taskkill /F /T /PID %i"%handle.pid , shell=True) - print("exit code: %d" % (t.proc.poll())) + print(f"exit code: {t.proc.poll()}") diff --git a/sources/shiboken6/libshiboken/embed/embedding_generator.py b/sources/shiboken6/libshiboken/embed/embedding_generator.py index 2c03cf686..a88da8d66 100644 --- a/sources/shiboken6/libshiboken/embed/embedding_generator.py +++ b/sources/shiboken6/libshiboken/embed/embedding_generator.py @@ -214,7 +214,8 @@ def _embed_bytefile(fin, fout, is_text): use_ord = sys.version_info[0] == 2 for i in range(0, len(binstr), 16): for c in bytes(binstr[i : i + 16]): - print("{:#4},".format(ord(c) if use_ord else c), file=fout, end="") + ord_c = ord(c) if use_ord else c + print(f"{ord_c:#4},", file=fout, end="") print(file=fout) print("/* End Of File */", file=fout) diff --git a/sources/shiboken6/shiboken_version.py b/sources/shiboken6/shiboken_version.py index 88b65353f..b5ebfa59c 100644 --- a/sources/shiboken6/shiboken_version.py +++ b/sources/shiboken6/shiboken_version.py @@ -51,5 +51,5 @@ pre_release_version = "1" if __name__ == '__main__': # Used by CMake. - print('{0};{1};{2};{3};{4}'.format(major_version, minor_version, patch_version, - release_version_type, pre_release_version)) + print(f'{major_version};{minor_version};{patch_version};' + f'{release_version_type};{pre_release_version}') diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/__feature__.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/__feature__.py index 48a47d511..0fa58d22f 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/__feature__.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/__feature__.py @@ -117,7 +117,7 @@ def _import(name, *args, **kwargs): if feature in _really_all_feature_names: flag |= globals()[feature] else: - raise SyntaxError("PySide feature {} is not defined".format(feature)) + raise SyntaxError(f"PySide feature {feature} is not defined") flag |= existing & 255 if isinstance(existing, int) and existing >= 0 else 0 pyside_feature_dict[importing_module] = flag diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/fix-complaints.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/fix-complaints.py index 284664aef..cc819e070 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/fix-complaints.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/fix-complaints.py @@ -60,8 +60,7 @@ offending_words = { } utf8_line = "# This Python file uses the following encoding: utf-8\n" -marker_line = "# It has been edited by {} .\n".format( - os.path.basename(__file__)) +marker_line = f"# It has been edited by {os.path.basename(__file__)} .\n" def patch_file(fname): with open(fname) as f: @@ -71,7 +70,7 @@ def patch_file(fname): for word, repl in offending_words.items(): if word in line: lines[idx] = line.replace(word, repl) - print("line:{!r} {!r}->{!r}".format(line, word, repl)) + print(f"line:{line!r} {word!r}->{repl!r}") if lines[0].strip() != utf8_line.strip(): lines[:0] = [utf8_line, "\n"] if lines[1] != marker_line: 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 6d832627e..99052e50e 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 @@ -110,7 +110,8 @@ class ExactEnumerator(object): if name not in ("object", "type"): name = base.__module__ + "." + name bases_list.append(name) - class_str = "{}({})".format(class_name, ", ".join(bases_list)) + bases_str = ', '.join(bases_list) + class_str = f"{class_name}({bases_str})" # class_members = inspect.getmembers(klass) # gives us also the inherited things. class_members = sorted(list(klass.__dict__.items())) 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 83da63891..268142db8 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/tool.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/lib/tool.py @@ -55,8 +55,9 @@ class SimpleNamespace(object): def __repr__(self): keys = sorted(self.__dict__) - items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys) - return "{}({})".format(type(self).__name__, ", ".join(items)) + items = (f"{k}={self.__dict__[k]!r}" for k in keys) + items_str = ', '.join(items) + return f"{type(self).__name__}({items_str})" def __eq__(self, other): return self.__dict__ == other.__dict__ diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/loader.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/loader.py index 5a056aafd..e685da166 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/loader.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/loader.py @@ -135,7 +135,7 @@ def put_into_package(package, module, override=None): if package: setattr(package, name, module) # put into sys.modules as a package to allow all import options - fullname = "{}.{}".format(_get_modname(package), name) if package else name + fullname = f"{_get_modname(package)}.{name}" if package else name _set_modname(module, fullname) # publish new dotted name in sys.modules sys.modules[fullname] = module @@ -147,7 +147,7 @@ def list_modules(message): if hasattr(value, "__file__")} print("SYS.MODULES", message, len(sys.modules), len(ext_modules)) for (name, module) in sorted(ext_modules.items()): - print(" {:23}".format(name), repr(module)[:70]) + print(f" {name:23}", repr(module)[:70]) orig_typing = True diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/mapping.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/mapping.py index 70bcc4822..97991d4f9 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/mapping.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/mapping.py @@ -103,7 +103,7 @@ class _NotCalled(str): real object is needed, the wrapper can simply be called. """ def __repr__(self): - return "{}({})".format(type(self).__name__, self) + return f"{type(self).__name__}({self})" def __call__(self): from shibokensupport.signature.mapping import __dict__ as namespace @@ -128,7 +128,7 @@ class Missing(_NotCalled): def __repr__(self): if USE_PEP563: return _NotCalled.__repr__(self) - return '{}("{}")'.format(type(self).__name__, self) + return f'{type(self).__name__}("{self}")' class Invalid(_NotCalled): @@ -149,8 +149,7 @@ class _Parameterized(object): self.__name__ = self.__class__.__name__ def __repr__(self): - return "{}({})".format( - type(self).__name__, self.type.__name__) + return f"{type(self).__name__}({self.type.__name__})" # Mark the primitive variables to be moved into the result. class ResultVariable(_Parameterized): diff --git a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/parser.py b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/parser.py index 49c0ca5be..d737c2a54 100644 --- a/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/parser.py +++ b/sources/shiboken6/shibokenmodule/files.dir/shibokensupport/signature/parser.py @@ -141,11 +141,11 @@ def _parse_line(line): def make_good_value(thing, valtype): try: if thing.endswith("()"): - thing = 'Default("{}")'.format(thing[:-2]) + thing = f'Default("{thing[:-2]}")' else: ret = eval(thing, namespace) if valtype and repr(ret).startswith("<"): - thing = 'Instance("{}")'.format(thing) + thing = f'Instance("{thing}")' return eval(thing, namespace) except Exception: pass @@ -153,7 +153,7 @@ def make_good_value(thing, valtype): def try_to_guess(thing, valtype): if "." not in thing and "(" not in thing: - text = "{}.{}".format(valtype, thing) + text = f"{valtype}.{thing}" ret = make_good_value(text, valtype) if ret is not None: return ret @@ -183,7 +183,7 @@ def _resolve_value(thing, valtype, line): map = type_map[valtype] # typing.Any: '_SpecialForm' object has no attribute '__name__' name = get_name(map) if hasattr(map, "__name__") else str(map) - thing = "zero({})".format(name) + thing = f"zero({name})" if thing in type_map: return type_map[thing] res = make_good_value(thing, valtype) @@ -194,11 +194,11 @@ def _resolve_value(thing, valtype, line): if res is not None: type_map[thing] = res return res - warnings.warn("""pyside_type_init: + warnings.warn(f"""pyside_type_init: - UNRECOGNIZED: {!r} - OFFENDING LINE: {!r} - """.format(thing, line), RuntimeWarning) + UNRECOGNIZED: {thing!r} + OFFENDING LINE: {line!r} + """, RuntimeWarning) return thing @@ -397,7 +397,8 @@ def fix_variables(props, line): if len(retvars) == 1: returntype = retvars[0] else: - typestr = "typing.Tuple[{}]".format(", ".join(map(to_string, retvars))) + retvars_str = ", ".join(map(to_string, retvars)) + typestr = f"typing.Tuple[{retvars_str}]" returntype = eval(typestr, namespace) props.annotations["return"] = returntype props.varnames = tuple(varnames) @@ -425,7 +426,7 @@ def fixup_multilines(lines): nmulti = len(multi_lines) if nmulti > 1: for idx, line in enumerate(multi_lines): - res.append("{}:{}".format(nmulti-idx-1, line)) + res.append(f"{nmulti-idx-1}:{line}") else: res.append(multi_lines[0]) multi_lines = [] @@ -436,7 +437,7 @@ def fixup_multilines(lines): def pyside_type_init(type_key, sig_strings): dprint() - dprint("Initialization of type key '{}'".format(type_key)) + dprint(f"Initialization of type key '{type_key}'") update_mapping() lines = fixup_multilines(sig_strings) ret = {} diff --git a/sources/shiboken6/tests/shiboken_paths.py b/sources/shiboken6/tests/shiboken_paths.py index 382079c36..29535f1b0 100644 --- a/sources/shiboken6/tests/shiboken_paths.py +++ b/sources/shiboken6/tests/shiboken_paths.py @@ -35,9 +35,9 @@ def get_dir_env_var(var_name): """Return a directory set by an environment variable""" result = os.environ.get(var_name) if not result: - raise ValueError('{} is not set!'.format(var_name)) + raise ValueError(f'{var_name} is not set!') if not os.path.isdir(result): - raise ValueError('{} is not a directory!'.format(result)) + raise ValueError(f'{result} is not a directory!') return result @@ -71,7 +71,7 @@ def _prepend_path_var(var_name, paths): old_paths = os.environ.get(var_name) new_paths = os.pathsep.join(paths) if old_paths: - new_paths += '{}{}'.format(os.pathsep, old_paths) + new_paths += f'{os.pathsep}{old_paths}' os.environ[var_name] = new_paths |