From ad44afed7d6e9343f3aee1710a15b4e903d15dcf Mon Sep 17 00:00:00 2001 From: Sourcery AI <> Date: Mon, 4 Dec 2023 15:31:32 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- build_scripts/build_usd.py | 149 +++---- cmake/macros/generateDocs.py | 6 +- cmake/macros/testWrapper.py | 4 +- .../usdMakeFileVariantModelAsset.py | 20 +- .../usd/examples/usdviewPlugins/sendMail.py | 76 +++- .../endToEnd/scripts/create_asset.py | 2 +- .../tutorials/endToEnd/scripts/create_shot.py | 2 +- .../tutorial_scripts/add_shadingVariants.py | 6 +- .../tutorial_scripts/layout_shot_s00_01.py | 2 +- .../traversingStage/traversingStage.py | 17 +- pxr/base/lib/gf/gfGenCode.py | 28 +- .../lib/gf/testenv/testGfDecomposeRotation.py | 27 +- pxr/base/lib/gf/testenv/testGfInterval.py | 5 +- pxr/base/lib/gf/testenv/testGfLine.py | 2 +- pxr/base/lib/gf/testenv/testGfLineSeg.py | 2 +- pxr/base/lib/gf/testenv/testGfMath.py | 2 +- pxr/base/lib/gf/testenv/testGfMatrix.py | 31 +- pxr/base/lib/gf/testenv/testGfPlane.py | 6 +- pxr/base/lib/gf/testenv/testGfQuaternion.py | 6 +- pxr/base/lib/gf/testenv/testGfRange.py | 7 +- pxr/base/lib/gf/testenv/testGfSize.py | 8 +- pxr/base/lib/gf/testenv/testGfVec.py | 31 +- pxr/base/lib/plug/testPlug.py | 55 ++- pxr/base/lib/tf/testenv/testTfFileUtils.py | 53 ++- pxr/base/lib/tf/testenv/testTfPython.py | 8 +- .../tf/testenv/testTfScriptModuleLoader.py | 2 +- pxr/base/lib/trace/__init__.py | 14 +- pxr/base/lib/vt/__init__.py | 3 +- pxr/base/lib/vt/testenv/testVtArray.py | 6 +- pxr/base/lib/vt/testenv/testVtValue.py | 2 +- pxr/usd/bin/usdcat/usdcat.py | 32 +- pxr/usd/bin/usddiff/usddiff.py | 39 +- pxr/usd/bin/usdedit/usdedit.py | 17 +- pxr/usd/lib/ar/testenv/testArAdvancedAPI.py | 14 +- pxr/usd/lib/kind/testenv/testKindRegistry.py | 2 +- .../pcp/testenv/testPcpCompositionResults.py | 3 +- pxr/usd/lib/pcp/testenv/testPcpInstanceKey.py | 3 +- pxr/usd/lib/pcp/testenv/testPcpMapFunction.py | 8 +- .../lib/pcp/testenv/testPcpPathTranslation.py | 2 +- .../pcp/testenv/testPcpPayloadDecorator.py | 74 ++-- pxr/usd/lib/sdf/__init__.py | 23 +- pxr/usd/lib/sdf/sdfGenAsciiParsers.py | 72 +-- pxr/usd/lib/sdf/testenv/testSdfCopyUtils.py | 10 +- pxr/usd/lib/sdf/testenv/testSdfPath2.py | 4 +- .../lib/sdf/testenv/testSdfPath2Construct.py | 4 +- pxr/usd/lib/sdf/testenv/testSdfPayload.py | 6 +- pxr/usd/lib/sdf/testenv/testSdfSpecHash.py | 7 +- .../sdf/testenv/testSdfTextReferenceParser.py | 2 +- .../usd/testenv/testUsdAttributeBlocking.py | 6 +- .../testenv/testUsdAttributeConnections.py | 120 +++-- pxr/usd/lib/usd/testenv/testUsdBug119633.py | 2 +- pxr/usd/lib/usd/testenv/testUsdBugs.py | 112 +++-- pxr/usd/lib/usd/testenv/testUsdClasses.py | 4 +- .../lib/usd/testenv/testUsdCollectionAPI.py | 9 +- .../usd/testenv/testUsdCreateProperties.py | 96 ++-- pxr/usd/lib/usd/testenv/testUsdDataFormats.py | 11 +- pxr/usd/lib/usd/testenv/testUsdEditTarget.py | 57 +-- pxr/usd/lib/usd/testenv/testUsdFileFormats.py | 10 +- pxr/usd/lib/usd/testenv/testUsdFlatten.py | 43 +- .../usd/testenv/testUsdFlattenProperties.py | 21 +- pxr/usd/lib/usd/testenv/testUsdInherits.py | 32 +- .../lib/usd/testenv/testUsdInstanceProxy.py | 6 +- pxr/usd/lib/usd/testenv/testUsdInstancing.py | 33 +- pxr/usd/lib/usd/testenv/testUsdMetadata.py | 70 +-- pxr/usd/lib/usd/testenv/testUsdModel.py | 10 +- pxr/usd/lib/usd/testenv/testUsdNotices.py | 18 +- pxr/usd/lib/usd/testenv/testUsdPayloads.py | 27 +- pxr/usd/lib/usd/testenv/testUsdPrimRange.py | 46 +- pxr/usd/lib/usd/testenv/testUsdPrims.py | 76 ++-- pxr/usd/lib/usd/testenv/testUsdReferences.py | 35 +- .../lib/usd/testenv/testUsdRelationships.py | 119 +++-- pxr/usd/lib/usd/testenv/testUsdSpecializes.py | 26 +- pxr/usd/lib/usd/testenv/testUsdStage.py | 188 ++++---- .../lib/usd/testenv/testUsdStageLoadUnload.py | 38 +- .../testenv/testUsdStagePopulationMasks.py | 2 +- pxr/usd/lib/usd/testenv/testUsdTimeOffsets.py | 19 +- pxr/usd/lib/usd/testenv/testUsdValueClips.py | 12 +- .../lib/usd/testenv/testUsdVariantEditing.py | 6 +- .../usd/testenv/testUsdVariantFallbacks.py | 9 +- pxr/usd/lib/usd/testenv/testUsdVariants.py | 6 +- pxr/usd/lib/usd/usdGenSchema.py | 214 ++++----- .../lib/usdGeom/testenv/testUsdGeomCamera.py | 4 +- .../testenv/testUsdGeomCollectionAPI.py | 5 +- .../testenv/testUsdGeomComputeAtTime.py | 6 +- .../usdGeom/testenv/testUsdGeomFaceSetAPI.py | 5 +- .../lib/usdGeom/testenv/testUsdGeomPrimvar.py | 26 +- .../usdGeom/testenv/testUsdGeomSchemata.py | 6 +- .../usdGeom/testenv/testUsdGeomXformable.py | 5 +- .../lib/usdRi/testenv/testUsdRiSchemata.py | 55 ++- .../testUsdShadeInterfaceInputConsumers.py | 60 ++- .../testenv/testUsdShadeMaterialAuthoring.py | 13 +- .../testUsdShadeMaterialBaseMaterial.py | 3 +- ...ShadeMaterialSpecializesBaseComposition.py | 8 +- .../testenv/testUsdShadeNodeGraphs.py | 28 +- pxr/usd/lib/usdSkel/examples.py | 3 +- .../lib/usdUI/testenv/testUsdUIBackdrop.py | 7 +- .../usdUI/testenv/testUsdUINodeGraphNode.py | 100 ++--- .../usdUI/testenv/testUsdUISceneGraphPrim.py | 22 +- ...estUsdUtilsCoalescingDiagnosticDelegate.py | 14 +- .../usdUtils/testenv/testUsdUtilsStitch.py | 18 +- .../testenv/testUsdUtilsStitchClips.py | 24 +- .../plugin/usdAbc/testenv/testUsdAbcCamera.py | 6 +- .../usdAbc/testenv/testUsdAbcInstancing.py | 4 +- .../testUsdviewNavigationKeys.py | 8 +- .../testUsdviewNoPlugins.py | 2 +- .../testUsdviewPrimPathBar.py | 2 +- .../testUsdviewPropertySearch.py | 4 +- pxr/usdImaging/bin/usdview/usdview.py | 2 +- pxr/usdImaging/lib/usdviewq/__init__.py | 2 +- pxr/usdImaging/lib/usdviewq/adjustClipping.py | 10 +- pxr/usdImaging/lib/usdviewq/appController.py | 414 ++++++++---------- pxr/usdImaging/lib/usdviewq/appEventFilter.py | 29 +- .../lib/usdviewq/arrayAttributeView.py | 9 +- .../lib/usdviewq/attributeValueEditor.py | 16 +- .../lib/usdviewq/attributeViewContextMenu.py | 21 +- pxr/usdImaging/lib/usdviewq/common.py | 60 ++- pxr/usdImaging/lib/usdviewq/constantGroup.py | 17 +- .../lib/usdviewq/customAttributes.py | 3 +- .../lib/usdviewq/layerStackContextMenu.py | 2 +- pxr/usdImaging/lib/usdviewq/plugin.py | 39 +- pxr/usdImaging/lib/usdviewq/prettyPrint.py | 6 +- .../lib/usdviewq/primContextMenuItems.py | 68 ++- pxr/usdImaging/lib/usdviewq/primViewItem.py | 21 +- .../lib/usdviewq/pythonInterpreter.py | 86 ++-- pxr/usdImaging/lib/usdviewq/rootDataModel.py | 17 +- .../lib/usdviewq/selectionDataModel.py | 57 +-- pxr/usdImaging/lib/usdviewq/settings.py | 11 +- pxr/usdImaging/lib/usdviewq/settings2.py | 67 ++- pxr/usdImaging/lib/usdviewq/stageView.py | 132 +++--- .../testenv/testUsdviewqConstantGroup.py | 6 +- .../testenv/testUsdviewqSelectionDataModel.py | 9 +- pxr/usdImaging/lib/usdviewq/usdviewApi.py | 12 +- .../lib/usdviewq/variantComboBox.py | 5 +- .../lib/usdviewq/viewSettingsDataModel.py | 26 +- third_party/houdini/lib/gusd/treemodel.py | 141 +++--- third_party/houdini/lib/gusd/treeview.py | 43 +- 136 files changed, 2099 insertions(+), 2057 deletions(-) diff --git a/build_scripts/build_usd.py b/build_scripts/build_usd.py index 37fb2a5ecb3..2077e9e7d01 100644 --- a/build_scripts/build_usd.py +++ b/build_scripts/build_usd.py @@ -76,10 +76,8 @@ def GetXcodeDeveloperDirectory(): if not MacOS(): return None - try: + with contextlib.suppress(subprocess.CalledProcessError): return subprocess.check_output("xcode-select -p").strip() - except subprocess.CalledProcessError: - pass return None def GetVisualStudioCompilerAndVersion(): @@ -89,12 +87,11 @@ def GetVisualStudioCompilerAndVersion(): if not Windows(): return None - msvcCompiler = find_executable('cl') - if msvcCompiler: - match = re.search( - "Compiler Version (\d+).(\d+).(\d+)", - subprocess.check_output("cl", stderr=subprocess.STDOUT)) - if match: + if msvcCompiler := find_executable('cl'): + if match := re.search( + "Compiler Version (\d+).(\d+).(\d+)", + subprocess.check_output("cl", stderr=subprocess.STDOUT), + ): return (msvcCompiler, tuple(int(v) for v in match.groups())) return None @@ -192,8 +189,7 @@ def RunCMake(context, force, extraArgs = None): # On Windows, we need to explicitly specify the generator to ensure we're # building a 64-bit project. (Surely there is a better way to do this?) if generator is None and Windows(): - msvcCompilerAndVersion = GetVisualStudioCompilerAndVersion() - if msvcCompilerAndVersion: + if msvcCompilerAndVersion := GetVisualStudioCompilerAndVersion(): _, version = msvcCompilerAndVersion if version >= MSVC_2017_COMPILER_VERSION: generator = "Visual Studio 15 2017 Win64" @@ -202,12 +198,8 @@ def RunCMake(context, force, extraArgs = None): if generator is not None: generator = '-G "{gen}"'.format(gen=generator) - - # On MacOS, enable the use of @rpath for relocatable builds. - osx_rpath = None - if MacOS(): - osx_rpath = "-DCMAKE_MACOSX_RPATH=ON" + osx_rpath = "-DCMAKE_MACOSX_RPATH=ON" if MacOS() else None with CurrentWorkingDirectory(buildDir): Run('cmake ' '-DCMAKE_INSTALL_PREFIX="{instDir}" ' @@ -234,9 +226,12 @@ def PatchFile(filename, patches): for (oldLine, newLine) in patches: newLines = [s.replace(oldLine, newLine) for s in newLines] if newLines != oldLines: - PrintInfo("Patching file {filename} (original in {oldFilename})..." - .format(filename=filename, oldFilename=filename + ".old")) - shutil.copy(filename, filename + ".old") + PrintInfo( + "Patching file {filename} (original in {oldFilename})...".format( + filename=filename, oldFilename=f"{filename}.old" + ) + ) + shutil.copy(filename, f"{filename}.old") open(filename, 'w').writelines(newLines) def DownloadURL(url, context, force, dontExtract = None): @@ -250,7 +245,7 @@ def DownloadURL(url, context, force, dontExtract = None): been extracted.""" with CurrentWorkingDirectory(context.srcDir): # Extract filename from URL and see if file already exists. - filename = url.split("/")[-1] + filename = url.split("/")[-1] if force and os.path.exists(filename): os.remove(filename) @@ -270,7 +265,7 @@ def DownloadURL(url, context, force, dontExtract = None): # Download to a temporary file and rename it to the expected # filename when complete. This ensures that incomplete downloads # will be retried if the script is run again. - tmpFilename = filename + ".tmp" + tmpFilename = f"{filename}.tmp" if os.path.exists(tmpFilename): os.remove(tmpFilename) @@ -364,7 +359,7 @@ def DownloadURL(url, context, force, dontExtract = None): # If extraction failed for whatever reason, assume the # archive file was bad and move it aside so that re-running # the script will try downloading and extracting again. - shutil.move(filename, filename + ".bad") + shutil.move(filename, f"{filename}.bad") raise RuntimeError("Failed to extract archive {filename}: {err}" .format(filename=filename, err=e)) @@ -378,8 +373,10 @@ def __init__(self, name, installer, *files): self.filesToCheck = files def Exists(self, context): - return all([os.path.isfile(os.path.join(context.instDir, f)) - for f in self.filesToCheck]) + return all( + os.path.isfile(os.path.join(context.instDir, f)) + for f in self.filesToCheck + ) class PythonDependency(object): def __init__(self, name, getInstructions, moduleNames): @@ -390,19 +387,17 @@ def __init__(self, name, getInstructions, moduleNames): def Exists(self, context): # If one of the modules in our list exists we are good for moduleName in self.moduleNames: - try: + with contextlib.suppress(subprocess.CalledProcessError): # Eat all output; we just care if the import succeeded or not. subprocess.check_output(shlex.split( 'python -c "import {module}"'.format(module=moduleName)), stderr=subprocess.STDOUT) return True - except subprocess.CalledProcessError: - pass return False def AnyPythonDependencies(deps): - return any([type(d) is PythonDependency for d in deps]) + return any(type(d) is PythonDependency for d in deps) ############################################################ # zlib @@ -433,7 +428,7 @@ def InstallBoost(context, force): dontExtract = ["*/doc/*", "*/libs/*/doc/*"] with CurrentWorkingDirectory(DownloadURL(BOOST_URL, context, force, - dontExtract)): + dontExtract)): bootstrap = "bootstrap.bat" if Windows() else "./bootstrap.sh" Run('{bootstrap} --prefix="{instDir}"' .format(bootstrap=bootstrap, instDir=context.instDir)) @@ -467,13 +462,8 @@ def InstallBoost(context, force): if Windows(): b2_settings.append("toolset=msvc-14.0") - - # Boost 1.61 doesn't support Visual Studio 2017. If that's what - # we're using then patch the project-config.jam file to hack in - # support. We'll get a lot of messages about an unknown compiler - # version but it will build. - msvcCompilerAndVersion = GetVisualStudioCompilerAndVersion() - if msvcCompilerAndVersion: + + if msvcCompilerAndVersion := GetVisualStudioCompilerAndVersion(): compiler, version = msvcCompilerAndVersion if version >= MSVC_2017_COMPILER_VERSION: PatchFile('project-config.jam', @@ -696,20 +686,13 @@ def InstallPtex_LinuxOrMacOS(context, force): def InstallOpenImageIO(context, force): with CurrentWorkingDirectory(DownloadURL(OIIO_URL, context, force)): - extraArgs = ['-DOIIO_BUILD_TOOLS=OFF', - '-DOIIO_BUILD_TESTS=OFF', - '-DUSE_PYTHON=OFF', - '-DSTOP_ON_WARNING=OFF'] - - # OIIO's FindOpenEXR module circumvents CMake's normal library - # search order, which causes versions of OpenEXR installed in - # /usr/local or other hard-coded locations in the module to - # take precedence over the version we've built, which would - # normally be picked up when we specify CMAKE_PREFIX_PATH. - # This may lead to undefined symbol errors at build or runtime. - # So, we explicitly specify the OpenEXR we want to use here. - extraArgs.append('-DOPENEXR_HOME="{instDir}"' - .format(instDir=context.instDir)) + extraArgs = [ + '-DOIIO_BUILD_TOOLS=OFF', + '-DOIIO_BUILD_TESTS=OFF', + '-DUSE_PYTHON=OFF', + '-DSTOP_ON_WARNING=OFF', + '-DOPENEXR_HOME="{instDir}"'.format(instDir=context.instDir), + ] # If Ptex support is disabled in USD, disable support in OpenImageIO # as well. This ensures OIIO doesn't accidentally pick up a Ptex @@ -739,13 +722,9 @@ def InstallOpenSubdiv(context, force): '-DNO_OPENCL=ON', '-DNO_DX=ON', '-DNO_TESTS=ON', + '-DGLEW_LOCATION="{instDir}"'.format(instDir=context.instDir), ] - # OpenSubdiv's FindGLEW module won't look in CMAKE_PREFIX_PATH, so - # we need to explicitly specify GLEW_LOCATION here. - extraArgs.append('-DGLEW_LOCATION="{instDir}"' - .format(instDir=context.instDir)) - # If Ptex support is disabled in USD, disable support in OpenSubdiv # as well. This ensures OSD doesn't accidentally pick up a Ptex # library outside of our build. @@ -862,17 +841,17 @@ def InstallUSD(context): extraArgs.append('-DBUILD_SHARED_LIBS=ON') elif context.buildMonolithic: extraArgs.append('-DPXR_BUILD_MONOLITHIC=ON') - + if context.buildDocs: extraArgs.append('-DPXR_BUILD_DOCUMENTATION=ON') else: extraArgs.append('-DPXR_BUILD_DOCUMENTATION=OFF') - + if context.buildTests: extraArgs.append('-DPXR_BUILD_TESTS=ON') else: extraArgs.append('-DPXR_BUILD_TESTS=OFF') - + if context.buildImaging: extraArgs.append('-DPXR_BUILD_IMAGING=ON') if context.enablePtex: @@ -898,12 +877,14 @@ def InstallUSD(context): if context.buildAlembic: extraArgs.append('-DPXR_BUILD_ALEMBIC_PLUGIN=ON') if context.enableHDF5: - extraArgs.append('-DPXR_ENABLE_HDF5_SUPPORT=ON') - - # CMAKE_PREFIX_PATH isn't sufficient for the FindHDF5 module - # to find the HDF5 we've built, so provide an extra hint. - extraArgs.append('-DHDF5_ROOT="{instDir}"' - .format(instDir=context.instDir)) + extraArgs.extend( + ( + '-DPXR_ENABLE_HDF5_SUPPORT=ON', + '-DHDF5_ROOT="{instDir}"'.format( + instDir=context.instDir + ), + ) + ) else: extraArgs.append('-DPXR_ENABLE_HDF5_SUPPORT=OFF') else: @@ -1114,7 +1095,7 @@ def __init__(self, args): # Directory where dependencies will be downloaded and extracted self.srcDir = (os.path.abspath(args.src) if args.src else os.path.join(self.usdInstDir, "src")) - + # Directory where USD and dependencies will be built self.buildDir = (os.path.abspath(args.build) if args.build else os.path.join(self.usdInstDir, "build")) @@ -1144,8 +1125,7 @@ def __init__(self, args): self.buildPython = args.build_python # - Imaging - self.buildImaging = (args.build_imaging == IMAGING or - args.build_imaging == USD_IMAGING) + self.buildImaging = args.build_imaging in [IMAGING, USD_IMAGING] self.enablePtex = self.buildImaging and args.enable_ptex # - USD Imaging @@ -1194,9 +1174,12 @@ def ForceBuildDependency(self, dep): extraPaths = [] extraPythonPaths = [] if Windows(): - extraPaths.append(os.path.join(context.instDir, "lib")) - extraPaths.append(os.path.join(context.instDir, "bin")) - + extraPaths.extend( + ( + os.path.join(context.instDir, "lib"), + os.path.join(context.instDir, "bin"), + ) + ) if extraPaths: paths = os.environ.get('PATH', '').split(os.pathsep) + extraPaths os.environ['PATH'] = os.pathsep.join(paths) @@ -1220,7 +1203,7 @@ def ForceBuildDependency(self, dep): requiredDependencies += [JPEG, TIFF, PNG, OPENEXR, GLEW, OPENIMAGEIO, OPENSUBDIV] - + if context.buildUsdImaging and context.buildPython: requiredDependencies += [PYOPENGL, PYSIDE] @@ -1286,7 +1269,7 @@ def ForceBuildDependency(self, dep): if not find_executable("doxygen"): PrintError("doxygen not found -- please install it and adjust your PATH") sys.exit(1) - + if not find_executable("dot"): PrintError("dot not found -- please install graphviz and adjust your " "PATH") @@ -1297,9 +1280,9 @@ def ForceBuildDependency(self, dep): # not found, so check for it here to avoid confusing users. This list of # PySide executable names comes from cmake/modules/FindPySide.cmake pysideUic = ["pyside-uic", "python2-pyside-uic", "pyside-uic-2.7"] - found_pysideUic = any([find_executable(p) for p in pysideUic]) + found_pysideUic = any(find_executable(p) for p in pysideUic) pyside2Uic = ["pyside2-uic", "python2-pyside2-uic", "pyside2-uic-2.7"] - found_pyside2Uic = any([find_executable(p) for p in pyside2Uic]) + found_pyside2Uic = any(find_executable(p) for p in pyside2Uic) if not found_pysideUic and not found_pyside2Uic: PrintError("pyside-uic not found -- please install PySide and adjust " "your PATH. (Note that this program may be named {0} " @@ -1367,11 +1350,9 @@ def ForceBuildDependency(self, dep): if args.dry_run: sys.exit(0) -# Scan for any dependencies that the user is required to install themselves -# and print those instructions first. -pythonDependencies = \ - [dep for dep in dependenciesToBuild if type(dep) is PythonDependency] -if pythonDependencies: +if pythonDependencies := [ + dep for dep in dependenciesToBuild if type(dep) is PythonDependency +]: for dep in pythonDependencies: Print(dep.getInstructions()) sys.exit(1) @@ -1406,14 +1387,10 @@ def ForceBuildDependency(self, dep): sys.exit(1) # Done. Print out a final status message. -requiredInPythonPath = set([ - os.path.join(context.usdInstDir, "lib", "python") -]) +requiredInPythonPath = {os.path.join(context.usdInstDir, "lib", "python")} requiredInPythonPath.update(extraPythonPaths) -requiredInPath = set([ - os.path.join(context.usdInstDir, "bin") -]) +requiredInPath = {os.path.join(context.usdInstDir, "bin")} requiredInPath.update(extraPaths) if Windows(): @@ -1440,7 +1417,7 @@ def ForceBuildDependency(self, dep): if context.buildMaya: Print("See documentation at http://openusd.org/docs/Maya-USD-Plugins.html " "for setting up the Maya plugin.\n") - + if context.buildKatana: Print("See documentation at http://openusd.org/docs/Katana-USD-Plugins.html " "for setting up the Katana plugin.\n") diff --git a/cmake/macros/generateDocs.py b/cmake/macros/generateDocs.py index 4dfc2f295cc..9c27c77cdcd 100644 --- a/cmake/macros/generateDocs.py +++ b/cmake/macros/generateDocs.py @@ -121,11 +121,11 @@ def _checkPath(path, ident, perm): elif not os.access(path, perm): permString = '-permission' if perm == os.W_OK: - permString = 'write'+permString + permString = f'write{permString}' elif perm == os.R_OK: - permString = 'read'+permString + permString = f'read{permString}' elif perm == os.X_OK: - permString = 'execute'+permString + permString = f'execute{permString}' sys.exit('Error: insufficient permission for path %s, ' '%s required.' % (path, permString)) diff --git a/cmake/macros/testWrapper.py b/cmake/macros/testWrapper.py index be0f552cbc2..424d6e8161d 100644 --- a/cmake/macros/testWrapper.py +++ b/cmake/macros/testWrapper.py @@ -176,9 +176,7 @@ def _splitCmd(cmd): # want the exit code 134 as that is what the script would return when run # from the shell. This is well defined to be 128 + (signal number). def _convertRetCode(retcode): - if retcode < 0: - return 128 + abs(retcode) - return retcode + return 128 + abs(retcode) if retcode < 0 else retcode def _getRedirects(out_redir, err_redir): return (open(out_redir, 'w') if out_redir else None, diff --git a/extras/usd/examples/usdMakeFileVariantModelAsset/usdMakeFileVariantModelAsset.py b/extras/usd/examples/usdMakeFileVariantModelAsset/usdMakeFileVariantModelAsset.py index 94cb42b350a..a21e6460c55 100644 --- a/extras/usd/examples/usdMakeFileVariantModelAsset/usdMakeFileVariantModelAsset.py +++ b/extras/usd/examples/usdMakeFileVariantModelAsset/usdMakeFileVariantModelAsset.py @@ -159,18 +159,18 @@ def CreateModelStage(assetName, "'variantFile1'") args = parser.parse_args() - + if not args.assetName or args.assetName == '': parser.error("No assetName specified") - - stage = CreateModelStage(args.assetName, - assetIdentifier=args.identifier, - kind=args.kind, - filesToReference=args.variantFiles, - variantSetName=args.variantSet, - defaultVariantSelection=args.defaultVariantSelection) - - if stage: + + if stage := CreateModelStage( + args.assetName, + assetIdentifier=args.identifier, + kind=args.kind, + filesToReference=args.variantFiles, + variantSetName=args.variantSet, + defaultVariantSelection=args.defaultVariantSelection, + ): stage.GetRootLayer().Save() exit(0) else: diff --git a/extras/usd/examples/usdviewPlugins/sendMail.py b/extras/usd/examples/usdviewPlugins/sendMail.py index f3a1a106378..8a0b7a5971a 100644 --- a/extras/usd/examples/usdviewPlugins/sendMail.py +++ b/extras/usd/examples/usdviewPlugins/sendMail.py @@ -62,11 +62,7 @@ def SendMail(usdviewApi): return False # set the image based on user config - if mailInfo.imagetype == "Window": - imagedata = windowShot - else: - imagedata = viewportShot - + imagedata = windowShot if mailInfo.imagetype == "Window" else viewportShot # verify we created an image correctly and could safely save it if not imagedata or not imagedata.save(tempimagefile.name): return False @@ -236,18 +232,64 @@ def _GenerateDefaultInfo(usdviewApi, dialog): camera = usdviewApi.currentGfCamera sendee = "" subject = 'Usdview Screenshot' - body = str("Usdview screenshot, taken " + currtime + "\n" + - "----------------------------------------" + "\n" + - "File: " - + str(usdviewApi.stageIdentifier) + "\n" + - "Selected Prim Paths: " - + ", ".join(map(str, usdviewApi.selectedPrims)) + "\n" + - "Current Frame: " - + str(usdviewApi.frame) + "\n" + - "Complexity: " - + str(usdviewApi.dataModel.viewSettings.complexity) + "\n" + - "Camera Info:\n" +str(camera) + "\n" + - "----------------------------------------" + "\n") + body = str( + ( + ( + ( + ( + ( + ( + ( + ( + ( + ( + ( + ( + ( + ( + f"Usdview screenshot, taken {currtime}" + + "\n" + + "----------------------------------------" + ) + + "\n" + ) + + "File: " + ) + + str( + usdviewApi.stageIdentifier + ) + + "\n" + ) + + "Selected Prim Paths: " + ) + + ", ".join( + map( + str, + usdviewApi.selectedPrims, + ) + ) + + "\n" + ) + + "Current Frame: " + ) + + str(usdviewApi.frame) + + "\n" + ) + + "Complexity: " + ) + + str(usdviewApi.dataModel.viewSettings.complexity) + + "\n" + ) + + "Camera Info:\n" + ) + + str(camera) + + "\n" + ) + + "----------------------------------------" + ) + + "\n" + ) + ) return EmailInfo(sender, sendee, subject, body) diff --git a/extras/usd/tutorials/endToEnd/scripts/create_asset.py b/extras/usd/tutorials/endToEnd/scripts/create_asset.py index a1d0e13533b..5472822cd73 100644 --- a/extras/usd/tutorials/endToEnd/scripts/create_asset.py +++ b/extras/usd/tutorials/endToEnd/scripts/create_asset.py @@ -60,7 +60,7 @@ def main(): if os.path.exists(outputDir): if not force: - parser.error('outputDir "%s" exists. Use -f to override' % outputDir) + parser.error(f'outputDir "{outputDir}" exists. Use -f to override') else: os.makedirs(outputDir) diff --git a/extras/usd/tutorials/endToEnd/scripts/create_shot.py b/extras/usd/tutorials/endToEnd/scripts/create_shot.py index ef8171e5b1b..068f114aaea 100644 --- a/extras/usd/tutorials/endToEnd/scripts/create_shot.py +++ b/extras/usd/tutorials/endToEnd/scripts/create_shot.py @@ -56,7 +56,7 @@ def main(): if os.path.exists(outputDir): if not force: - parser.error('outputDir "%s" exists. Use -f to override' % outputDir) + parser.error(f'outputDir "{outputDir}" exists. Use -f to override') else: os.makedirs(outputDir) diff --git a/extras/usd/tutorials/endToEnd/tutorial_scripts/add_shadingVariants.py b/extras/usd/tutorials/endToEnd/tutorial_scripts/add_shadingVariants.py index 7ef58d3f4ee..1d5eafca729 100644 --- a/extras/usd/tutorials/endToEnd/tutorial_scripts/add_shadingVariants.py +++ b/extras/usd/tutorials/endToEnd/tutorial_scripts/add_shadingVariants.py @@ -92,7 +92,7 @@ def _AddShadingToBall(stage): # write to the shadingVariant. with shadingVariant.GetVariantEditContext(): whichBall = variantName.split('_')[-1] - texPath = os.path.join(texDir, 'ball%s.tex' % whichBall) + texPath = os.path.join(texDir, f'ball{whichBall}.tex') # in the current variant, modify the color _SetParameters(ballTextureNode, [ ('filename', Sdf.ValueTypeNames.String, texPath), @@ -101,8 +101,8 @@ def _AddShadingToBall(stage): # set the display color for hydra _SetDisplayColor(mesh, color) - # currently not doing anything with decoration, but we could maybe - # use this to make the solid vs. stripes. + # currently not doing anything with decoration, but we could maybe + # use this to make the solid vs. stripes. # now make the variant selection 'Cue' instead of the last variant that we # created above. diff --git a/extras/usd/tutorials/endToEnd/tutorial_scripts/layout_shot_s00_01.py b/extras/usd/tutorials/endToEnd/tutorial_scripts/layout_shot_s00_01.py index 7009e07fa4d..4633213ead8 100644 --- a/extras/usd/tutorials/endToEnd/tutorial_scripts/layout_shot_s00_01.py +++ b/extras/usd/tutorials/endToEnd/tutorial_scripts/layout_shot_s00_01.py @@ -72,7 +72,7 @@ def _SetupBilliards(stage): # deactivate everything that isn't 8, 9, 1, 4. We accumulate the prims we # want to deactivate so that we don't delete while iterating. roomProps = stage.GetPrimAtPath('/World/sets/Room_set/Props') - keepers = set(['Ball_%d' % i for i in [1, 9, 8, 4] ]) + keepers = {'Ball_%d' % i for i in [1, 9, 8, 4]} toDeactivate = [] for child in roomProps.GetChildren(): if child.GetName() not in keepers: diff --git a/extras/usd/tutorials/traversingStage/traversingStage.py b/extras/usd/tutorials/traversingStage/traversingStage.py index 4f7f70dd629..7acb896dd06 100644 --- a/extras/usd/tutorials/traversingStage/traversingStage.py +++ b/extras/usd/tutorials/traversingStage/traversingStage.py @@ -27,9 +27,12 @@ # section 1 stage = Usd.Stage.Open("RefExample.usda") -assert([x for x in stage.Traverse()] == [stage.GetPrimAtPath("/refSphere"), - stage.GetPrimAtPath("/refSphere/world"), stage.GetPrimAtPath("/refSphere2"), - stage.GetPrimAtPath("/refSphere2/world")]) +assert list(stage.Traverse()) == [ + stage.GetPrimAtPath("/refSphere"), + stage.GetPrimAtPath("/refSphere/world"), + stage.GetPrimAtPath("/refSphere2"), + stage.GetPrimAtPath("/refSphere2/world"), +] # section 2 assert([x for x in stage.Traverse() if UsdGeom.Sphere(x)] == @@ -38,7 +41,7 @@ # section 3 treeIter = iter(Usd.PrimRange.PreAndPostVisit(stage.GetPseudoRoot())) - + treeIterExpectedResults = [(stage.GetPrimAtPath("/"), False), (stage.GetPrimAtPath("/refSphere"), False), (stage.GetPrimAtPath("/refSphere/world"), False), @@ -59,5 +62,7 @@ stage.SetEditTarget(stage.GetSessionLayer()) Usd.Prim.SetActive(ref2Prim, False) -assert ([x for x in stage.Traverse()] == [stage.GetPrimAtPath("/refSphere"), - stage.GetPrimAtPath("/refSphere/world")]) +assert list(stage.Traverse()) == [ + stage.GetPrimAtPath("/refSphere"), + stage.GetPrimAtPath("/refSphere/world"), +] diff --git a/pxr/base/lib/gf/gfGenCode.py b/pxr/base/lib/gf/gfGenCode.py index 8af7f15bb2d..cc4016591bd 100644 --- a/pxr/base/lib/gf/gfGenCode.py +++ b/pxr/base/lib/gf/gfGenCode.py @@ -115,13 +115,10 @@ def GenerateFromTemplates(env, templates, suffix, outputPath, verbose=True): 'Template Error: {}: {}'.format(err, tmplName) def ScalarSuffix(scl): - if scl == 'GfHalf': - return 'h' - else: - return scl[0] + return 'h' if scl == 'GfHalf' else scl[0] def VecName(dim, scl): - return 'GfVec%s%s' % (dim, ScalarSuffix(scl)) + return f'GfVec{dim}{ScalarSuffix(scl)}' def Eps(scl): return '0.001' if scl == 'GfHalf' else 'GF_MIN_VECTOR_LENGTH' @@ -151,14 +148,14 @@ def GetVecSpecs(): # GfRange def GetRangeSpecs(): def RngName(dim, scl): - return 'GfRange%s%s' % (dim, ScalarSuffix(scl)) + return f'GfRange{dim}{ScalarSuffix(scl)}' def MinMaxType(dim, scl): return scl if dim == 1 else VecName(dim, scl) def MinMaxParm(dim, scl): t = MinMaxType(dim, scl) - return t + ' ' if dim == 1 else 'const %s &' % t + return f'{t} ' if dim == 1 else f'const {t} &' scalarTypes = ['double', 'float'] dimensions = [1, 2, 3] @@ -182,7 +179,7 @@ def MinMaxParm(dim, scl): # GfQuat def GetQuatSpecs(): def QuatName(scl): - return 'GfQuat%s' % ScalarSuffix(scl) + return f'GfQuat{ScalarSuffix(scl)}' scalarTypes = ['double', 'float', 'GfHalf'] quatSpecs = sorted( @@ -203,7 +200,7 @@ def QuatName(scl): # GfMatrix def GetMatrixSpecs(dim): def MatrixName(dim, scl): - return 'GfMatrix%s%s' % (dim, ScalarSuffix(scl)) + return f'GfMatrix{dim}{ScalarSuffix(scl)}' scalarTypes = ['double', 'float'] dimensions = [dim] @@ -247,11 +244,14 @@ def ValidateFiles(srcDir, dstDir): continue dstContent, srcContent = open(dstFile).read(), open(srcFile).read() if dstContent != srcContent: - diff = '\n'.join(difflib.unified_diff( - srcContent.split('\n'), - dstContent.split('\n'), - 'Source ' + os.path.basename(srcFile), - 'Generated ' + os.path.basename(dstFile))) + diff = '\n'.join( + difflib.unified_diff( + srcContent.split('\n'), + dstContent.split('\n'), + f'Source {os.path.basename(srcFile)}', + f'Generated {os.path.basename(dstFile)}', + ) + ) diffs.append(diff) continue diff --git a/pxr/base/lib/gf/testenv/testGfDecomposeRotation.py b/pxr/base/lib/gf/testenv/testGfDecomposeRotation.py index bfec6ea07c9..e7495a57d93 100644 --- a/pxr/base/lib/gf/testenv/testGfDecomposeRotation.py +++ b/pxr/base/lib/gf/testenv/testGfDecomposeRotation.py @@ -52,11 +52,8 @@ def ComposeRotation(rotOrder, rotVals): swMat = Gf.Matrix3d(swRot) return Gf.Matrix4d(twMat * fbMat * lrMat * swMat, Gf.Vec3d(0)) -def IsMatrixClose (x, y, epsilon=1e-6): - for i in range(4): - if not Gf.IsClose(x.GetRow(i), y.GetRow(i), epsilon): - return False - return True +def IsMatrixClose(x, y, epsilon=1e-6): + return all(Gf.IsClose(x.GetRow(i), y.GetRow(i), epsilon) for i in range(4)) class TestGfDecomposeRotation(unittest.TestCase): @@ -83,21 +80,21 @@ def _TestDecomposeRotation(self, useHint = False, expectedResult = None): self.log.info("_TestDecomposeRotation") - self.log.info(" rot = " + str(rot)) - self.log.info(" rotOrder = " + str(rotOrder)) - self.log.info(" thetaTwHint = " + str(thetaTwHint)) - self.log.info(" thetaFBHint = " + str(thetaFBHint)) - self.log.info(" thetaLRHint = " + str(thetaLRHint)) - self.log.info(" thetaSwHint = " + str(thetaSwHint)) - self.log.info(" useHint = " + str(useHint)) - self.log.info(" expectedResult = " + str(expectedResult)) + self.log.info(f" rot = {str(rot)}") + self.log.info(f" rotOrder = {str(rotOrder)}") + self.log.info(f" thetaTwHint = {str(thetaTwHint)}") + self.log.info(f" thetaFBHint = {str(thetaFBHint)}") + self.log.info(f" thetaLRHint = {str(thetaLRHint)}") + self.log.info(f" thetaSwHint = {str(thetaSwHint)}") + self.log.info(f" useHint = {str(useHint)}") + self.log.info(f" expectedResult = {str(expectedResult)}") self.log.info("") # Do a special test for the passed in rotation order if expectedResult # was passed in for checking. if expectedResult != None: result = \ - Gf.Rotation.DecomposeRotation(rot, + Gf.Rotation.DecomposeRotation(rot, twAxis = axes[rotOrder][2], fbAxis = axes[rotOrder][0], lrAxis = axes[rotOrder][1], @@ -115,7 +112,7 @@ def _TestDecomposeRotation(self, # for all rotation orders. for key in axes.keys(): result = \ - Gf.Rotation.DecomposeRotation(rot, + Gf.Rotation.DecomposeRotation(rot, twAxis = axes[key][2], fbAxis = axes[key][0], lrAxis = axes[key][1], diff --git a/pxr/base/lib/gf/testenv/testGfInterval.py b/pxr/base/lib/gf/testenv/testGfInterval.py index 3435b97a60c..d0b1c1ed752 100644 --- a/pxr/base/lib/gf/testenv/testGfInterval.py +++ b/pxr/base/lib/gf/testenv/testGfInterval.py @@ -31,12 +31,11 @@ class TestGfInterval(unittest.TestCase): def runTest(self): - testIntervals = [] inf = float("inf") # Empty interval i0 = Gf.Interval() - testIntervals.append(i0) + testIntervals = [i0] self.assertTrue(i0.isEmpty) # Non-empty: [1,1] @@ -264,7 +263,7 @@ def runTest(self): # Test representations self.assertTrue(i1.min == eval(repr(i1)).min and \ - i1.max == eval(repr(i1)).max, ("repr")) + i1.max == eval(repr(i1)).max, ("repr")) self.assertTrue(len(str(Gf.Interval())), ("str")) diff --git a/pxr/base/lib/gf/testenv/testGfLine.py b/pxr/base/lib/gf/testenv/testGfLine.py index dc4f4a2505a..2d12f4b55e3 100644 --- a/pxr/base/lib/gf/testenv/testGfLine.py +++ b/pxr/base/lib/gf/testenv/testGfLine.py @@ -29,7 +29,7 @@ from pxr import Gf def err( msg ): - return "ERROR: " + msg + " failed" + return f"ERROR: {msg} failed" class TestGfLine(unittest.TestCase): diff --git a/pxr/base/lib/gf/testenv/testGfLineSeg.py b/pxr/base/lib/gf/testenv/testGfLineSeg.py index 1966f891b54..be00a2dfebf 100644 --- a/pxr/base/lib/gf/testenv/testGfLineSeg.py +++ b/pxr/base/lib/gf/testenv/testGfLineSeg.py @@ -29,7 +29,7 @@ from pxr import Gf def err( msg ): - return "ERROR: " + msg + " failed" + return f"ERROR: {msg} failed" class TestGfLineSeg(unittest.TestCase): diff --git a/pxr/base/lib/gf/testenv/testGfMath.py b/pxr/base/lib/gf/testenv/testGfMath.py index c62bb87553d..9cb8abe7b1f 100644 --- a/pxr/base/lib/gf/testenv/testGfMath.py +++ b/pxr/base/lib/gf/testenv/testGfMath.py @@ -29,7 +29,7 @@ from pxr.Gf import * def err( msg ): - return "ERROR: " + msg + " failed" + return f"ERROR: {msg} failed" class TestGfMath(unittest.TestCase): diff --git a/pxr/base/lib/gf/testenv/testGfMatrix.py b/pxr/base/lib/gf/testenv/testGfMatrix.py index f69bf0178ca..9bc46459409 100644 --- a/pxr/base/lib/gf/testenv/testGfMatrix.py +++ b/pxr/base/lib/gf/testenv/testGfMatrix.py @@ -37,10 +37,9 @@ def makeValue( Value, vals ): if Value == float: return Value(vals[0]) - else: - v = Value() - for i in range(v.dimension): - v[i] = vals[i] + v = Value() + for i in range(v.dimension): + v[i] = vals[i] return v class TestGfMatrix(unittest.TestCase): @@ -172,13 +171,19 @@ def test_Other(self): self.assertEqual(m[-1], makeValue(Vec, (3,1,4,1))) m = Matrix() - m[0,0] = 1; m[1,0] = 2; m[0,1] = 3; m[1,1] = 4 + m[0,0] = 1 + m[1,0] = 2 + m[0,1] = 3 + m[1,1] = 4 self.assertTrue(m[0,0] == 1 and m[1,0] == 2 and m[0,1] == 3 and m[1,1] == 4) - + m = Matrix() - m[-1,-1] = 1; m[-2,-1] = 2; m[-1,-2] = 3; m[-2,-2] = 4 + m[-1,-1] = 1 + m[-2,-1] = 2 + m[-1,-2] = 3 + m[-2,-2] = 4 self.assertTrue(m[-1,-1] == 1 and m[-2,-1] == 2 and m[-1,-2] == 3 and m[-2,-2] == 4) - + m = Matrix() for i in range(m.dimension[0]): for j in range(m.dimension[1]): @@ -195,7 +200,7 @@ def test_Other(self): self.assertEqual(Matrix(3).GetDeterminant(), 3 ** Matrix.dimension[0]) self.assertEqual(len(Matrix()), Matrix.dimension[0]) - + # Test GetRow, GetRow3, GetColumn m = Matrix(1) for i in range(m.dimension[0]): @@ -210,7 +215,7 @@ def test_Other(self): for j in range(m.dimension[1]): self.assertEqual(m.GetColumn(j), makeValue(Vec, tuple(j+x*m.dimension[0] \ - for x in range(m.dimension[0])) )) + for x in range(m.dimension[0])) )) # Test SetRow, SetRow3, SetColumn m = Matrix(1) @@ -233,7 +238,7 @@ def test_Other(self): v = makeValue(Vec, tuple(j+x*m.dimension[0] for x in range(m.dimension[0])) ) m.SetColumn(i, v) self.assertEqual(v, m.GetColumn(i)) - + m = Matrix(4) m *= Matrix(1./4) self.assertEqual(m, Matrix(1)) @@ -270,7 +275,7 @@ def test_Other(self): self.assertEqual(Matrix(2) * makeValue(Vecf, (3,1,4,1)), makeValue(Vecf, (6,2,8,2))) self.assertEqual(makeValue(Vecf, (3,1,4,1)) * Matrix(2), makeValue(Vecf, (6,2,8,2))) - self.assertTrue(2 in Matrix(2) and not 4 in Matrix(2)) + self.assertTrue(2 in Matrix(2) and 4 not in Matrix(2)) m = Matrix(1) try: @@ -777,7 +782,7 @@ def AssertDeterminant(m, det): AssertDeterminant(m2, det2) AssertDeterminant(m3, det3) AssertDeterminant(m4, det4) - AssertDeterminant(m1 * m1, det1 * det1) + AssertDeterminant(m1 * m1, det1**2) AssertDeterminant(m1 * m4, det1 * det4) AssertDeterminant(m1 * m3 * m4, det1 * det3 * det4) AssertDeterminant(m1 * m3 * m4 * m2, det1 * det3 * det4 * det2) diff --git a/pxr/base/lib/gf/testenv/testGfPlane.py b/pxr/base/lib/gf/testenv/testGfPlane.py index d4a31fa75ec..6a02de3f3c0 100644 --- a/pxr/base/lib/gf/testenv/testGfPlane.py +++ b/pxr/base/lib/gf/testenv/testGfPlane.py @@ -29,7 +29,7 @@ from pxr import Gf def err( msg ): - return "ERROR: " + msg + " failed" + return f"ERROR: {msg} failed" class TestGfBBox3d(unittest.TestCase): @@ -75,8 +75,8 @@ def test_Operators(self): p1 = Gf.Plane(Gf.Vec3d(1,1,1), 10) p2 = Gf.Plane(Gf.Vec3d(1,1,1), 20) self.assertEqual(p1, Gf.Plane(Gf.Vec3d(1,1,1), 10), err("equality")) - self.assertTrue(not p1 == p2, err("equality")) - self.assertTrue(not p1 != Gf.Plane(Gf.Vec3d(1,1,1), 10), err("inequality")) + self.assertTrue(p1 != p2, err("equality")) + self.assertTrue(p1 == Gf.Plane(Gf.Vec3d(1,1,1), 10), err("inequality")) self.assertTrue(p1 != p2, err("inequality")) def test_Methods(self): diff --git a/pxr/base/lib/gf/testenv/testGfQuaternion.py b/pxr/base/lib/gf/testenv/testGfQuaternion.py index a1257deff3d..868e5ac2fc8 100644 --- a/pxr/base/lib/gf/testenv/testGfQuaternion.py +++ b/pxr/base/lib/gf/testenv/testGfQuaternion.py @@ -99,13 +99,13 @@ def test_Operators(self): q *= 10 self.assertEqual(q, Gf.Quaternion(10,Gf.Vec3d(20,30,40))) - q = q * 10 + q *= 10 self.assertEqual(q, Gf.Quaternion(100,Gf.Vec3d(200,300,400))) - q = 10 * q + q *= 10 self.assertEqual(q, Gf.Quaternion(1000,Gf.Vec3d(2000,3000,4000))) q /= 100 self.assertEqual(q, Gf.Quaternion(10,Gf.Vec3d(20,30,40))) - q = q / 10 + q /= 10 self.assertEqual(q, Gf.Quaternion(1,Gf.Vec3d(2,3,4))) q += q diff --git a/pxr/base/lib/gf/testenv/testGfRange.py b/pxr/base/lib/gf/testenv/testGfRange.py index dfa01203928..6a22325a8cf 100644 --- a/pxr/base/lib/gf/testenv/testGfRange.py +++ b/pxr/base/lib/gf/testenv/testGfRange.py @@ -30,10 +30,9 @@ def makeValue( Value, vals ): if Value == float: return Value(vals[0]) - else: - v = Value() - for i in range(v.dimension): - v[i] = vals[i] + v = Value() + for i in range(v.dimension): + v[i] = vals[i] return v class TestGfRange(unittest.TestCase): diff --git a/pxr/base/lib/gf/testenv/testGfSize.py b/pxr/base/lib/gf/testenv/testGfSize.py index 95b785d98e7..58c12798262 100644 --- a/pxr/base/lib/gf/testenv/testGfSize.py +++ b/pxr/base/lib/gf/testenv/testGfSize.py @@ -42,7 +42,7 @@ def runTest(self): # constructors self.assertIsInstance(Size(), Size) self.assertIsInstance(Size(Size()), Size) - + if Size.dimension == 2: self.assertIsInstance(Size(Gf.Vec2i()), Size) self.assertIsInstance(Size(3, 4), Size) @@ -86,9 +86,9 @@ def runTest(self): self.assertEqual(makeValue(Size,(10,20,30)) / 10, makeValue(Size,(1,2,3))) self.assertEqual(s1, eval(repr(s1))) - + self.assertTrue(len(str(makeValue(Size,(1,2,3))))) - + # indexing s = Size() s[-1] = 3 @@ -97,7 +97,7 @@ def runTest(self): self.assertEqual(len(s), s.dimension) s = makeValue(Size, (1,2,3)) - self.assertTrue(not 10 in s) + self.assertTrue(10 not in s) # expect error with self.assertRaises(IndexError): diff --git a/pxr/base/lib/gf/testenv/testGfVec.py b/pxr/base/lib/gf/testenv/testGfVec.py index 8c71adce0a5..08fcdf00cd4 100644 --- a/pxr/base/lib/gf/testenv/testGfVec.py +++ b/pxr/base/lib/gf/testenv/testGfVec.py @@ -81,22 +81,17 @@ def vecWithType( vecType, type ): return Gf.Vec4h elif type == 'i': return Gf.Vec4i - assert False, "No valid conversion for " + vecType + " to type " + type + assert False, f"No valid conversion for {vecType} to type {type}" return None def checkVec( vec, values ): - for i in range(len(vec)): - if vec[i] != values[i]: - return False - return True + return all(vec[i] == values[i] for i in range(len(vec))) def checkVecDot( v1, v2, dp ): if len(v1) != len(v2): return False - checkdp = 0 - for i in range(len(v1)): - checkdp += v1[i] * v2[i] + checkdp = sum(v1[i] * v2[i] for i in range(len(v1))) return checkdp == dp @@ -132,15 +127,15 @@ def ConstructorsTest(self, Vec): v = Vec(3,1,4,1) self.assertTrue(checkVec( v, values )) else: - self.assertTrue(False, "No explicit constructor check for " + Vec) + self.assertTrue(False, f"No explicit constructor check for {Vec}") # constructor taking single scalar value. v = Vec(0) - self.assertTrue(all([x == 0 for x in v])) + self.assertTrue(all(x == 0 for x in v)) v = Vec(1) - self.assertTrue(all([x == 1 for x in v])) + self.assertTrue(all(x == 1 for x in v)) v = Vec(2) - self.assertTrue(all([x == 2 for x in v])) + self.assertTrue(all(x == 2 for x in v)) # conversion from other types to this float type. if isFloatingPoint(Vec): @@ -230,7 +225,7 @@ def OperatorsTest(self, Vec): self.assertEqual(v1, eval(repr(v1))) # string - self.assertTrue(len(str(Vec())) > 0) + self.assertTrue(str(Vec()) != "") # indexing v = Vec() @@ -249,16 +244,16 @@ def OperatorsTest(self, Vec): v = Vec() value = [3, 1, 4, 1] SetVec( v, value ) - value = v[0:v.dimension] + value = v[:v.dimension] self.assertEqual(v[:], value) self.assertEqual(v[:2], value[:2]) - self.assertEqual(v[0:2], value[0:2]) + self.assertEqual(v[:2], value[:2]) self.assertEqual(v[-2:], value[-2:]) self.assertEqual(v[1:1], []) if v.dimension > 2: - self.assertEqual(v[0:3:2], [3, 4]) + self.assertEqual(v[:3:2], [3, 4]) v[:2] = (8, 9) checkVec(v, [8, 9, 4, 1]) @@ -291,9 +286,9 @@ def MethodsTest(self, Vec): SetVec( v1, [3, 1, 4, 1] ) l = Gf.GetLength( v1 ) l2 = v1.GetLength() - self.assertTrue(Gf.IsClose(l, l2, eps), repr(l) + ' ' + repr(l2)) + self.assertTrue(Gf.IsClose(l, l2, eps), f'{repr(l)} {repr(l2)}') self.assertTrue(Gf.IsClose(l, math.sqrt(Gf.Dot(v1, v1)), eps), \ - ' '.join([repr(x) for x in [l, v1, math.sqrt(Gf.Dot(v1, v1))]])) + ' '.join([repr(x) for x in [l, v1, math.sqrt(Gf.Dot(v1, v1))]])) # Normalize... SetVec( v1, [3, 1, 4, 1] ) diff --git a/pxr/base/lib/plug/testPlug.py b/pxr/base/lib/plug/testPlug.py index 377e66632f4..0d99de7dbd4 100644 --- a/pxr/base/lib/plug/testPlug.py +++ b/pxr/base/lib/plug/testPlug.py @@ -31,10 +31,10 @@ # Test plugins are installed relative to this script testRoot = os.path.join(os.path.dirname(__file__), 'PlugPlugins') -testPluginsDso = testRoot + '/lib' -testPluginsPython = testRoot + '/lib/python' -testPluginsDsoSearch = testPluginsDso + '/*/Resources/' -testPluginsPythonSearch = testPluginsPython + '/**/' +testPluginsDso = f'{testRoot}/lib' +testPluginsPython = f'{testRoot}/lib/python' +testPluginsDsoSearch = f'{testPluginsDso}/*/Resources/' +testPluginsPythonSearch = f'{testPluginsPython}/**/' # Append the sys.path so that we will be able to load python plugins sys.path.append(testPluginsPython) @@ -95,26 +95,43 @@ def setUpClass(cls): def test_Registration(self): # Verify we received the appropriate notification self.assertEqual(self.listener1.numReceived, 1) - self.assertEqual(set([p.name for p in self.listener1.newPlugins]), - set(['TestPlugDso1', 'TestPlugDso2', 'TestPlugDso3', - 'TestPlugDsoUnloadable'])) + self.assertEqual( + {p.name for p in self.listener1.newPlugins}, + { + 'TestPlugDso1', + 'TestPlugDso2', + 'TestPlugDso3', + 'TestPlugDsoUnloadable', + }, + ) # Verify we received the appropriate notification self.assertEqual(self.listener2.numReceived, 2) - self.assertEqual(set([p.name for p in self.listener2.newPlugins]), - set(['TestPlugDso1', 'TestPlugDso2', 'TestPlugDso3', - 'TestPlugDsoUnloadable', - 'TestPlugModule1', 'TestPlugModule2', 'TestPlugModule3', - 'TestPlugModuleDepBadBase', 'TestPlugModuleDepBadDep', - 'TestPlugModuleDepBadDep2', 'TestPlugModuleDepBadLoad', - 'TestPlugModuleDepCycle', - 'TestPlugModuleLoaded', 'TestPlugModuleLoadedBadBase', - 'TestPlugModuleUnloadable'])) + self.assertEqual( + {p.name for p in self.listener2.newPlugins}, + { + 'TestPlugDso1', + 'TestPlugDso2', + 'TestPlugDso3', + 'TestPlugDsoUnloadable', + 'TestPlugModule1', + 'TestPlugModule2', + 'TestPlugModule3', + 'TestPlugModuleDepBadBase', + 'TestPlugModuleDepBadDep', + 'TestPlugModuleDepBadDep2', + 'TestPlugModuleDepBadLoad', + 'TestPlugModuleDepCycle', + 'TestPlugModuleLoaded', + 'TestPlugModuleLoadedBadBase', + 'TestPlugModuleUnloadable', + }, + ) # Check available subclasses of TestPlugBase<1> base1Subclasses = Tf.Type.FindByName('_TestPlugBase<1>').GetAllDerivedTypes() base1SubclassesExpected = \ - ('_TestPlugDerived0', 'TestPlugDerived1', + ('_TestPlugDerived0', 'TestPlugDerived1', 'TestPlugModule1.TestPlugPythonDerived1', 'TestPlugModuleLoaded.TestPlugPythonLoaded', 'TestPlugModuleLoadedBadBase.TestPlugPythonLoadedBadBase', @@ -275,12 +292,12 @@ def test_ErrorCases(self): self.assertEqual(listener.numReceived, 0) # try to register an incomplete plugin - badPluginPath = testPluginsDso + '/TestPlugDsoIncomplete.framework/Resources/' + badPluginPath = f'{testPluginsDso}/TestPlugDsoIncomplete.framework/Resources/' Plug.Registry().RegisterPlugins(badPluginPath) self.assertEqual(listener.numReceived, 0) # try to register an incomplete python plugin path - badPluginPath = testPluginsPython + '/TestPlugModuleIncomplete' + badPluginPath = f'{testPluginsPython}/TestPlugModuleIncomplete' Plug.Registry().RegisterPlugins(badPluginPath) self.assertEqual(listener.numReceived, 0) diff --git a/pxr/base/lib/tf/testenv/testTfFileUtils.py b/pxr/base/lib/tf/testenv/testTfFileUtils.py index d96d34b6770..8246aae6c17 100644 --- a/pxr/base/lib/tf/testenv/testTfFileUtils.py +++ b/pxr/base/lib/tf/testenv/testTfFileUtils.py @@ -67,9 +67,8 @@ class TestFileUtils(unittest.TestCase): def CreateFile(self, filename, data): """ Create file and register for cleanup""" - f = open(filename,"w") - f.write(data) - f.close() + with open(filename,"w") as f: + f.write(data) self.files.append(filename) def CreateSymlink(self, filename, linkname): @@ -127,15 +126,15 @@ def VerifyDirStructure(self, rootDir): ''' self.assertTrue(os.path.isdir(rootDir)) - self.assertTrue(os.path.isdir("%s/sub1" % rootDir)) - self.assertTrue(os.path.isdir("%s/sub2" % rootDir)) - self.assertTrue(os.path.isdir("%s/sub3" % rootDir)) - self.assertTrue(os.path.isdir("%s/sub1/sub1sub1" % rootDir)) - self.assertTrue(os.path.isdir("%s/sub1/sub1sub2" % rootDir)) - self.assertTrue(os.path.isdir("%s/sub2/sub2sub1" % rootDir)) - self.assertTrue(os.path.isdir("%s/sub2/sub2sub2" % rootDir)) - self.assertTrue(os.path.isdir("%s/sub3/sub3sub1" % rootDir)) - self.assertTrue(os.path.isdir("%s/sub3/sub3sub2" % rootDir)) + self.assertTrue(os.path.isdir(f"{rootDir}/sub1")) + self.assertTrue(os.path.isdir(f"{rootDir}/sub2")) + self.assertTrue(os.path.isdir(f"{rootDir}/sub3")) + self.assertTrue(os.path.isdir(f"{rootDir}/sub1/sub1sub1")) + self.assertTrue(os.path.isdir(f"{rootDir}/sub1/sub1sub2")) + self.assertTrue(os.path.isdir(f"{rootDir}/sub2/sub2sub1")) + self.assertTrue(os.path.isdir(f"{rootDir}/sub2/sub2sub2")) + self.assertTrue(os.path.isdir(f"{rootDir}/sub3/sub3sub1")) + self.assertTrue(os.path.isdir(f"{rootDir}/sub3/sub3sub2")) def VerifyDirAndFileStructure(self, rootDir): ''' @@ -145,21 +144,21 @@ def VerifyDirAndFileStructure(self, rootDir): self.VerifyDirStructure(rootDir) - self.assertTrue(os.path.isfile("%s/a" % rootDir)) - self.assertTrue(os.path.isfile("%s/b" % rootDir)) - self.assertTrue(os.path.isfile("%s/c" % rootDir)) + self.assertTrue(os.path.isfile(f"{rootDir}/a")) + self.assertTrue(os.path.isfile(f"{rootDir}/b")) + self.assertTrue(os.path.isfile(f"{rootDir}/c")) - self.assertTrue(os.path.isfile("%s/sub1/a" % rootDir)) - self.assertTrue(os.path.isfile("%s/sub1/b" % rootDir)) - self.assertTrue(os.path.isfile("%s/sub1/c" % rootDir)) + self.assertTrue(os.path.isfile(f"{rootDir}/sub1/a")) + self.assertTrue(os.path.isfile(f"{rootDir}/sub1/b")) + self.assertTrue(os.path.isfile(f"{rootDir}/sub1/c")) - self.assertTrue(os.path.isfile("%s/sub2/a" % rootDir)) - self.assertTrue(os.path.isfile("%s/sub2/b" % rootDir)) - self.assertTrue(os.path.isfile("%s/sub2/c" % rootDir)) + self.assertTrue(os.path.isfile(f"{rootDir}/sub2/a")) + self.assertTrue(os.path.isfile(f"{rootDir}/sub2/b")) + self.assertTrue(os.path.isfile(f"{rootDir}/sub2/c")) - self.assertTrue(os.path.isfile("%s/sub3/a" % rootDir)) - self.assertTrue(os.path.isfile("%s/sub3/b" % rootDir)) - self.assertTrue(os.path.isfile("%s/sub3/c" % rootDir)) + self.assertTrue(os.path.isfile(f"{rootDir}/sub3/a")) + self.assertTrue(os.path.isfile(f"{rootDir}/sub3/b")) + self.assertTrue(os.path.isfile(f"{rootDir}/sub3/c")) def setUp(self): """ Setup of test directories and symlinks""" @@ -231,12 +230,10 @@ def test_Touch(self): def PrintTestLinks(self): mtime = Lstat(self.Links[0][0]) - self.log.info('%s %s %s' % ( - mtime, Strftime(mtime), self.Links[0][0])) + self.log.info(f'{mtime} {Strftime(mtime)} {self.Links[0][0]}') for sp,dp in self.Links: mtime = Lstat(dp) - self.log.info('%s %s %s -> %s' % ( - mtime, Strftime(mtime), dp, sp)) + self.log.info(f'{mtime} {Strftime(mtime)} {dp} -> {sp}') def RemoveTestLinks(self): allFiles = set() diff --git a/pxr/base/lib/tf/testenv/testTfPython.py b/pxr/base/lib/tf/testenv/testTfPython.py index e1ec42c8406..655cb56633c 100644 --- a/pxr/base/lib/tf/testenv/testTfPython.py +++ b/pxr/base/lib/tf/testenv/testTfPython.py @@ -43,7 +43,7 @@ def f3(arg1, arg2): print 'args', arg1, arg2 def f4(stringArg): - return 'got string ' + stringArg + return f'got string {stringArg}' class MyBase(Tf._TestBase): def __init__(self): @@ -233,9 +233,9 @@ def test_EnumValuesRemovedFromTypeScope(self): self.assertTrue(Tf._Enum.Two == 2) self.assertTrue(Tf._Alpha == 3) - self.assertTrue(1 == Tf._Enum.One) - self.assertTrue(2 == Tf._Enum.Two) - self.assertTrue(3 == Tf._Alpha) + self.assertTrue(Tf._Enum.One == 1) + self.assertTrue(Tf._Enum.Two == 2) + self.assertTrue(Tf._Alpha == 3) self.assertTrue(Tf._Alpha | Tf._Alpha is Tf._Alpha) self.assertTrue(Tf._Alpha & Tf._Alpha is Tf._Alpha) diff --git a/pxr/base/lib/tf/testenv/testTfScriptModuleLoader.py b/pxr/base/lib/tf/testenv/testTfScriptModuleLoader.py index 01c9d916c59..4e06d2588e9 100644 --- a/pxr/base/lib/tf/testenv/testTfScriptModuleLoader.py +++ b/pxr/base/lib/tf/testenv/testTfScriptModuleLoader.py @@ -43,7 +43,7 @@ # Turn on script module loader debug output. Tf.Debug.SetDebugSymbolsByName('TF_SCRIPT_MODULE_LOADER', True) -prefix = Tf.__package__ + '.testenv.testTfScriptModuleLoader_' +prefix = f'{Tf.__package__}.testenv.testTfScriptModuleLoader_' def Import(name): exec "import " + prefix + name diff --git a/pxr/base/lib/trace/__init__.py b/pxr/base/lib/trace/__init__.py index e0fca7a5ee4..1221096ff9a 100644 --- a/pxr/base/lib/trace/__init__.py +++ b/pxr/base/lib/trace/__init__.py @@ -51,23 +51,19 @@ def TraceFunction(obj, isFree=True): global collector.""" collector = Collector() - + def decorate(func): import inspect if inspect.ismethod(func): callableTypeLabel = 'method' - classLabel = func.im_class.__name__+'.' + classLabel = f'{func.im_class.__name__}.' else: callableTypeLabel = 'func' classLabel = '' module = inspect.getmodule(func) - if module is not None: - moduleLabel = module.__name__+'.' - else: - moduleLabel = '' - + moduleLabel = f'{module.__name__}.' if module is not None else '' label = 'Python {0}: {1}{2}{3}'.format( callableTypeLabel, moduleLabel, @@ -93,9 +89,7 @@ def TraceMethod(obj): # Remove any private stuff, like test classes, if we are not being # imported from a test. -try: +with contextlib.suppress(Exception): from . import __DOC __DOC.Execute(locals()) del __DOC -except Exception: - pass diff --git a/pxr/base/lib/vt/__init__.py b/pxr/base/lib/vt/__init__.py index 66becd95c2f..ea22dbe85fc 100644 --- a/pxr/base/lib/vt/__init__.py +++ b/pxr/base/lib/vt/__init__.py @@ -50,8 +50,7 @@ def _CopyArrayFromBufferFuncs(moduleContents): for funcName, func in funcs.iteritems(): className = funcName[:-len('FromBuffer')] - cls = classes.get(className) - if cls: + if cls := classes.get(className): setattr(cls, 'FromBuffer', staticmethod(func)) setattr(cls, 'FromNumpy', staticmethod(func)) diff --git a/pxr/base/lib/vt/testenv/testVtArray.py b/pxr/base/lib/vt/testenv/testVtArray.py index cb72f449435..256b91a301e 100644 --- a/pxr/base/lib/vt/testenv/testVtArray.py +++ b/pxr/base/lib/vt/testenv/testVtArray.py @@ -220,8 +220,10 @@ def test_Numpy(self): src = Vt.DoubleArray(length, fill) result = Array.FromNumpy(numpy.array(src, copy=False)) self.assertEqual(len(list(result)), expLen) - self.assertTrue(all([x == expVal for x in result]), \ - '%s != %s' % (list(result), [expVal]*len(list(result)))) + self.assertTrue( + all(x == expVal for x in result), + f'{list(result)} != {[expVal] * len(list(result))}', + ) # Formerly failed, now produces a 1-d length-1 array. self.assertTrue(Vt.Vec3dArray.FromNumpy( diff --git a/pxr/base/lib/vt/testenv/testVtValue.py b/pxr/base/lib/vt/testenv/testVtValue.py index 05cf1f5fc30..c74bb802272 100644 --- a/pxr/base/lib/vt/testenv/testVtValue.py +++ b/pxr/base/lib/vt/testenv/testVtValue.py @@ -33,7 +33,7 @@ def err( msg ): global status status += 1 - return "ERROR: " + msg + " failed" + return f"ERROR: {msg} failed" class TestVtValue(unittest.TestCase): diff --git a/pxr/usd/bin/usdcat/usdcat.py b/pxr/usd/bin/usdcat/usdcat.py index 2925f8bf1f6..a62f6dc1e7f 100644 --- a/pxr/usd/bin/usdcat/usdcat.py +++ b/pxr/usd/bin/usdcat/usdcat.py @@ -92,12 +92,12 @@ def main(): # exactly one input file. if args.out: if os.path.isfile(args.out) and not os.access(args.out, os.W_OK): - _Err("%s: error: no write permission for existing output file '%s'" - % (parser.prog, args.out)) + _Err( + f"{parser.prog}: error: no write permission for existing output file '{args.out}'" + ) return 1 if len(args.inputFiles) != 1: - _Err("%s: error: must supply exactly one input file with -o/--out" % - parser.prog) + _Err(f"{parser.prog}: error: must supply exactly one input file with -o/--out") return 1 ext = os.path.splitext(args.out)[1][1:] if args.usdFormat: @@ -108,11 +108,8 @@ def main(): formatArgsDict.update(dict(format=args.usdFormat)) from pxr import Sdf if Sdf.FileFormat.FindByExtension(ext) is None: - _Err("%s: error: unknown output file extension '.%s'" - % (parser.prog, ext)) + _Err(f"{parser.prog}: error: unknown output file extension '.{ext}'") return 1 - # If --out was not specified, then --usdFormat must be unspecified or must - # be 'usda'. elif args.usdFormat and args.usdFormat != 'usda': _Err("%s: error: can only write 'usda' format to stdout; specify an " "output file with -o/--out to write other formats" % parser.prog) @@ -122,7 +119,7 @@ def main(): if args.populationMask: if not args.flatten: # You can only mask a stage, not a layer. - _Err("%s: error: --mask requires --flatten" % parser.prog) + _Err(f"{parser.prog}: error: --mask requires --flatten") return 1 args.populationMask = args.populationMask.replace(',', ' ').split() @@ -144,7 +141,7 @@ def main(): if not usdData: raise Exception("Unknown error") except Exception as e: - _Err("Failed to open '%s' - %s" % (inputFile, e)) + _Err(f"Failed to open '{inputFile}' - {e}") exitCode = 1 continue @@ -154,28 +151,27 @@ def main(): usdData.Export(args.out, args=formatArgsDict) except Exception as e: # Let the user know an error occurred. - _Err("Error exporting '%s' to '%s' - %s" % - (inputFile, args.out, e)) + _Err(f"Error exporting '{inputFile}' to '{args.out}' - {e}") # If the output file exists, let's try to rename it with # '.quarantine' appended and let the user know. Do this # after the above error report because os.rename() can # fail and we don't want to lose the above error. if os.path.isfile(args.out): - newName = args.out + '.quarantine' + newName = f'{args.out}.quarantine' try: os.rename(args.out, newName) - _Err("Possibly corrupt output file renamed to %s" % - (newName, )) + _Err(f"Possibly corrupt output file renamed to {newName}") except Exception as e: - _Err("Failed to rename possibly corrupt output " + - "file from %s to %s" % (args.out, newName)) + _Err( + f"Failed to rename possibly corrupt output file from {args.out} to {newName}" + ) exitCode = 1 else: try: sys.stdout.write(usdData.ExportToString()) except Exception as e: - _Err("Error writing '%s' to stdout; %s" % (inputFile, e)) + _Err(f"Error writing '{inputFile}' to stdout; {e}") exitCode = 1 return exitCode diff --git a/pxr/usd/bin/usddiff/usddiff.py b/pxr/usd/bin/usddiff/usddiff.py index 53d0d7ea6b9..3f9cbd984a1 100644 --- a/pxr/usd/bin/usddiff/usddiff.py +++ b/pxr/usd/bin/usddiff/usddiff.py @@ -52,8 +52,7 @@ def _generateCatCommand(usdcatCmd, inPath, outPath, flatten=None, fmt=None): def _findExe(name): from distutils.spawn import find_executable - cmd = find_executable(name) - if cmd: + if cmd := find_executable(name): return cmd if isWindows: # find_executable under Windows only returns *.EXE files @@ -79,8 +78,7 @@ def _findDiffTools(): # prefer USD_DIFF, then DIFF, else use the internal unified diff. diffCmd = (os.environ.get('USD_DIFF') or os.environ.get('DIFF')) if diffCmd and not _findExe(diffCmd): - _exit("Error: Failed to find diff tool %s." % (diffCmd, ), - ERROR_EXIT_CODE) + _exit(f"Error: Failed to find diff tool {diffCmd}.", ERROR_EXIT_CODE) return (usdcatCmd, diffCmd) @@ -102,15 +100,12 @@ def _getFileFormat(path): versionSpecifierPos = prunedExtension.rfind('#') if versionSpecifierPos != -1: prunedExtension = prunedExtension[:versionSpecifierPos] - + fileFormat = Sdf.FileFormat.FindByExtension(prunedExtension) # Don't check if file exists - this should be handled by resolver (and # path may not exist / have been fetched yet) - if fileFormat: - return fileFormat.formatId - - return None + return fileFormat.formatId if fileFormat else None def _convertTo(inPath, outPath, usdcatCmd, flatten=None, fmt=None): # Just copy empty files -- we want something to diff against but @@ -134,9 +129,11 @@ def _tryEdit(fileName, tempFileName, usdcatCmd, fileType, flattened): _exit('Error: Cannot write out flattened result.', ERROR_EXIT_CODE) if not os.access(fileName, os.W_OK): - _exit('Error: Cannot write to %s, insufficient permissions' % fileName, - ERROR_EXIT_CODE) - + _exit( + f'Error: Cannot write to {fileName}, insufficient permissions', + ERROR_EXIT_CODE, + ) + return _convertTo(tempFileName, fileName, usdcatCmd, flatten=None, fmt=fileType) def _runDiff(baseline, comparison, flatten, noeffect): @@ -275,19 +272,21 @@ def validateFiles(): dirpath = args[0] files = set(map(os.path.relpath, args[1:])) dirfiles = listFiles(dirpath) - return ([], - [(join(dirpath, p), p) for p in files & dirfiles], - [p for p in files - dirfiles]) - # FILES... DIR + return ( + [], + [(join(dirpath, p), p) for p in files & dirfiles], + list(files - dirfiles), + ) elif not any(map(isdir, stats[:-1])) and isdir(stats[-1]): validateFiles() dirpath = args[-1] files = set(map(os.path.relpath, args[:-1])) dirfiles = listFiles(dirpath) - return ([p for p in files - dirfiles], - [(p, join(dirpath, p)) for p in files & dirfiles], - []) - # FILE FILE or DIR DIR + return ( + list(files - dirfiles), + [(p, join(dirpath, p)) for p in files & dirfiles], + [], + ) elif len(args) == 2: # DIR DIR if all(map(isdir, stats)): diff --git a/pxr/usd/bin/usdedit/usdedit.py b/pxr/usd/bin/usdedit/usdedit.py index ad95106785e..78bc7a71683 100644 --- a/pxr/usd/bin/usdedit/usdedit.py +++ b/pxr/usd/bin/usdedit/usdedit.py @@ -29,8 +29,7 @@ def _findExe(name): from distutils.spawn import find_executable - cmd = find_executable(name) - if cmd: + if cmd := find_executable(name): return cmd if isWindows: # find_executable under Windows only returns *.EXE files @@ -60,7 +59,7 @@ def _findEditorTools(usdFileName, readOnly): _findExe("emacs") or _findExe("vim") or _findExe("notepad")) - + if not editorCmd: sys.exit("Error: Couldn't find a suitable text editor to use. Expected " "$USD_EDITOR or $EDITOR to be set, or emacs/vim/notepad to " @@ -68,9 +67,8 @@ def _findEditorTools(usdFileName, readOnly): # special handling for emacs users if 'emacs' in editorCmd: - title = '"usdedit %s%s"' % ("--noeffect " if readOnly else "", - usdFileName) - editorCmd += " -name %s" % title + title = f'"usdedit {"--noeffect " if readOnly else ""}{usdFileName}"' + editorCmd += f" -name {title}" return (usdcatCmd, editorCmd) @@ -98,9 +96,9 @@ def _generateTemporaryFile(usdcatCmd, usdFileName, readOnly, prefix): def _editTemporaryFile(editorCmd, usdaFileName): # check the timestamp before updating a file's mtime initialTimeStamp = os.path.getmtime(usdaFileName) - os.system(editorCmd + ' ' + usdaFileName) + os.system(f'{editorCmd} {usdaFileName}') newTimeStamp = os.path.getmtime(usdaFileName) - + # indicate whether the file was changed return initialTimeStamp != newTimeStamp @@ -110,8 +108,7 @@ def _writeOutChanges(temporaryFileName, permanentFileName): temporaryLayer = Sdf.Layer.FindOrOpen(temporaryFileName) if not temporaryLayer: - sys.exit("Error: Failed to open temporary layer %s." \ - %temporaryFileName) + sys.exit(f"Error: Failed to open temporary layer {temporaryFileName}.") # Note that we attempt to overwrite the permanent file's contents # rather than explicitly creating a new layer. This avoids aligning diff --git a/pxr/usd/lib/ar/testenv/testArAdvancedAPI.py b/pxr/usd/lib/ar/testenv/testArAdvancedAPI.py index 5bc222fc1ba..2f3a44ed3f8 100644 --- a/pxr/usd/lib/ar/testenv/testArAdvancedAPI.py +++ b/pxr/usd/lib/ar/testenv/testArAdvancedAPI.py @@ -30,7 +30,7 @@ # Test plugins are installed relative to this script testRoot = os.path.join(os.path.dirname(__file__), 'ArPlugins') -testPluginsDsoSearch = testRoot + '/lib/*/Resources/' +testPluginsDsoSearch = f'{testRoot}/lib/*/Resources/' # Disable standard plugin search paths to give our # test a stable environment. @@ -46,10 +46,14 @@ def test_GetAvailableResolvers(self): pr = Plug.Registry() plugins = pr.RegisterPlugins(testPluginsDsoSearch) self.assertEqual(len(plugins), 1) - self.assertEqual(set(pr.GetAllDerivedTypes('ArResolver')), - set([Tf.Type.FindByName('ArDefaultResolver'), - Tf.Type.FindByName('_TestResolver1'), - Tf.Type.FindByName('_TestResolver2')])) + self.assertEqual( + set(pr.GetAllDerivedTypes('ArResolver')), + { + Tf.Type.FindByName('ArDefaultResolver'), + Tf.Type.FindByName('_TestResolver1'), + Tf.Type.FindByName('_TestResolver2'), + }, + ) # Set _TestResolver2 to be the preferred resolver; # otherwise, _TestResolver1 would be initially constructed diff --git a/pxr/usd/lib/kind/testenv/testKindRegistry.py b/pxr/usd/lib/kind/testenv/testKindRegistry.py index 49b8ef7bd61..cd3c8dce4e7 100644 --- a/pxr/usd/lib/kind/testenv/testKindRegistry.py +++ b/pxr/usd/lib/kind/testenv/testKindRegistry.py @@ -28,7 +28,7 @@ class TestKindRegistry(unittest.TestCase): def test_Basic(self): # Register python module plugins - Plug.Registry().RegisterPlugins(os.getcwd() + "/**/") + Plug.Registry().RegisterPlugins(f"{os.getcwd()}/**/") reg = Kind.Registry() self.assertTrue(reg) diff --git a/pxr/usd/lib/pcp/testenv/testPcpCompositionResults.py b/pxr/usd/lib/pcp/testenv/testPcpCompositionResults.py index 1d987343f5d..5b018330c3e 100644 --- a/pxr/usd/lib/pcp/testenv/testPcpCompositionResults.py +++ b/pxr/usd/lib/pcp/testenv/testPcpCompositionResults.py @@ -92,8 +92,7 @@ def GetLayerLabel(layer): def WalkNodes(node): yield node for child in node.children: - for descendant in WalkNodes(child): - yield descendant + yield from WalkNodes(child) # Dump the layer stack. errors = [] diff --git a/pxr/usd/lib/pcp/testenv/testPcpInstanceKey.py b/pxr/usd/lib/pcp/testenv/testPcpInstanceKey.py index e4cddc72279..d3abf1d109b 100644 --- a/pxr/usd/lib/pcp/testenv/testPcpInstanceKey.py +++ b/pxr/usd/lib/pcp/testenv/testPcpInstanceKey.py @@ -28,8 +28,7 @@ class TestPcpInstanceKey(unittest.TestCase): def _LoadPcpCache(self, layerPath): rootLayer = Sdf.Layer.FindOrOpen(layerPath) - cache = Pcp.Cache(Pcp.LayerStackIdentifier(rootLayer), usd=True) - return cache + return Pcp.Cache(Pcp.LayerStackIdentifier(rootLayer), usd=True) def _GetInstanceKey(self, cache, primPath): (pi, err) = cache.ComputePrimIndex(primPath) diff --git a/pxr/usd/lib/pcp/testenv/testPcpMapFunction.py b/pxr/usd/lib/pcp/testenv/testPcpMapFunction.py index fc4efd09a31..7a2f3182914 100644 --- a/pxr/usd/lib/pcp/testenv/testPcpMapFunction.py +++ b/pxr/usd/lib/pcp/testenv/testPcpMapFunction.py @@ -32,11 +32,9 @@ Sdf.Path('/a/b/c') ] -testMapFuncs = [] - # Test null function null = Pcp.MapFunction() -testMapFuncs.append(null) +testMapFuncs = [null] assert null.isNull assert not null.isIdentity assert null.timeOffset == Sdf.LayerOffset() @@ -150,9 +148,7 @@ assert m6.timeOffset == offset2 assert m5.Compose(m6).timeOffset == (offset1 * offset2) -testMapFuncs.append(m5) -testMapFuncs.append(m6) - +testMapFuncs.extend((m5, m6)) # Test equality/inequality for i in range(len(testMapFuncs)): for j in range(len(testMapFuncs)): diff --git a/pxr/usd/lib/pcp/testenv/testPcpPathTranslation.py b/pxr/usd/lib/pcp/testenv/testPcpPathTranslation.py index db805fda488..e02eea1be02 100644 --- a/pxr/usd/lib/pcp/testenv/testPcpPathTranslation.py +++ b/pxr/usd/lib/pcp/testenv/testPcpPathTranslation.py @@ -28,7 +28,7 @@ class TestPcpPathTranslation(unittest.TestCase): def _GetPcpCacheForLayer(self, rootLayerPath): rootLayer = Sdf.Layer.FindOrOpen(rootLayerPath) - self.assertTrue(rootLayer, "Cannot open layer %s" % (rootLayerPath)) + self.assertTrue(rootLayer, f"Cannot open layer {rootLayerPath}") return Pcp.Cache(Pcp.LayerStackIdentifier(rootLayer)) diff --git a/pxr/usd/lib/pcp/testenv/testPcpPayloadDecorator.py b/pxr/usd/lib/pcp/testenv/testPcpPayloadDecorator.py index 935e9037acb..dd99e423271 100644 --- a/pxr/usd/lib/pcp/testenv/testPcpPayloadDecorator.py +++ b/pxr/usd/lib/pcp/testenv/testPcpPayloadDecorator.py @@ -49,13 +49,11 @@ def Compose(self, value): def _DecoratePayload(self, primIndexPath, payload, context): return self._GetArgs(context) def _IsFieldRelevantForDecoration(self, field): - return (field == "documentation" or - field == "kind") + return field in ["documentation", "kind"] def _IsFieldChangeRelevantForDecoration(self, primIndexPath, siteLayer, sitePath, field, oldVal, newVal): - assert (field == "documentation" or - field == "kind") + assert field in ["documentation", "kind"] return True class TestPcpPayloadDecorator(unittest.TestCase): @@ -82,34 +80,33 @@ def test_Basic(self): payloadLayerFile = 'basic/payload.sdf' payloadLayerId = Sdf.Layer.CreateIdentifier( payloadLayerFile, {'doc':'instance','kind':'ref'}) - assert Sdf.Layer.Find(payloadLayerId), \ - "Failed to find expected payload layer '%s'" % payloadLayerId + assert Sdf.Layer.Find( + payloadLayerId + ), f"Failed to find expected payload layer '{payloadLayerId}'" # Test that authoring a new value for the relevant fields # causes the prim to be significantly changed. with Pcp._TestChangeProcessor(cache) as cp: rootLayer.GetPrimAtPath('/Instance') \ - .SetInfo('documentation', 'updated_instance') - assert cp.GetSignificantChanges() == ['/Instance'], \ - "Got significant changes %s" % cp.GetSignificantChanges() - assert cp.GetSpecChanges() == [], \ - "Got spec changes %s" % cp.GetSpecChanges() - assert cp.GetPrimChanges() == [], \ - "Got prim changes %s" % cp.GetPrimChanges() - + .SetInfo('documentation', 'updated_instance') + assert cp.GetSignificantChanges() == [ + '/Instance' + ], f"Got significant changes {cp.GetSignificantChanges()}" + assert cp.GetSpecChanges() == [], f"Got spec changes {cp.GetSpecChanges()}" + assert cp.GetPrimChanges() == [], f"Got prim changes {cp.GetPrimChanges()}" + (pi, err) = cache.ComputePrimIndex('/Instance') assert Sdf.Layer.Find(payloadLayerId) with Pcp._TestChangeProcessor(cache) as cp: rootLayer.GetPrimAtPath('/Instance') \ - .SetInfo('kind', 'updated_instance') - assert cp.GetSignificantChanges() == ['/Instance'], \ - "Got significant changes %s" % cp.GetSignificantChanges() - assert cp.GetSpecChanges() == [], \ - "Got spec changes %s" % cp.GetSpecChanges() - assert cp.GetPrimChanges() == [], \ - "Got prim changes %s" % cp.GetPrimChanges() + .SetInfo('kind', 'updated_instance') + assert cp.GetSignificantChanges() == [ + '/Instance' + ], f"Got significant changes {cp.GetSignificantChanges()}" + assert cp.GetSpecChanges() == [], f"Got spec changes {cp.GetSpecChanges()}" + assert cp.GetPrimChanges() == [], f"Got prim changes {cp.GetPrimChanges()}" (pi, err) = cache.ComputePrimIndex('/Instance') @@ -121,13 +118,12 @@ def test_Basic(self): # does not cause any changes. with Pcp._TestChangeProcessor(cache) as cp: rootLayer.GetPrimAtPath('/Instance') \ - .SetInfo('comment', 'fooooo') - assert cp.GetSignificantChanges() == [], \ - "Got significant changes %s" % cp.GetSignificantChanges() - assert cp.GetSpecChanges() == [], \ - "Got spec changes %s" % cp.GetSpecChanges() - assert cp.GetPrimChanges() == [], \ - "Got prim changes %s" % cp.GetPrimChanges() + .SetInfo('comment', 'fooooo') + assert ( + cp.GetSignificantChanges() == [] + ), f"Got significant changes {cp.GetSignificantChanges()}" + assert cp.GetSpecChanges() == [], f"Got spec changes {cp.GetSpecChanges()}" + assert cp.GetPrimChanges() == [], f"Got prim changes {cp.GetPrimChanges()}" def TestSiblingStrength(): '''Test that Pcp.PayloadDecorator is invoked and that the @@ -206,23 +202,21 @@ def _IsFieldChangeRelevantForDecoration(self, primIndexPath, # significant change. with Pcp._TestChangeProcessor(cache) as cp: rootLayer.GetPrimAtPath('/Instance').SetInfo('documentation', 'foo') - assert cp.GetSignificantChanges() == ['/Instance'], \ - "Got significant changes %s" % cp.GetSignificantChanges() - assert cp.GetSpecChanges() == [], \ - "Got spec changes %s" % cp.GetSpecChanges() - assert cp.GetPrimChanges() == [], \ - "Got prim changes %s" % cp.GetPrimChanges() + assert cp.GetSignificantChanges() == [ + '/Instance' + ], f"Got significant changes {cp.GetSignificantChanges()}" + assert cp.GetSpecChanges() == [], f"Got spec changes {cp.GetSpecChanges()}" + assert cp.GetPrimChanges() == [], f"Got prim changes {cp.GetPrimChanges()}" # Other changes aren't relevant, so no changes should be # reported. with Pcp._TestChangeProcessor(cache) as cp: rootLayer.GetPrimAtPath('/Instance').SetInfo('documentation', 'bar') - assert cp.GetSignificantChanges() == [], \ - "Got significant changes %s" % cp.GetSignificantChanges() - assert cp.GetSpecChanges() == [], \ - "Got spec changes %s" % cp.GetSpecChanges() - assert cp.GetPrimChanges() == [], \ - "Got prim changes %s" % cp.GetPrimChanges() + assert ( + cp.GetSignificantChanges() == [] + ), f"Got significant changes {cp.GetSignificantChanges()}" + assert cp.GetSpecChanges() == [], f"Got spec changes {cp.GetSpecChanges()}" + assert cp.GetPrimChanges() == [], f"Got prim changes {cp.GetPrimChanges()}" if __name__ == "__main__": unittest.main() diff --git a/pxr/usd/lib/sdf/__init__.py b/pxr/usd/lib/sdf/__init__.py index 0b930e0a4c1..9f4e289be2a 100644 --- a/pxr/usd/lib/sdf/__init__.py +++ b/pxr/usd/lib/sdf/__init__.py @@ -37,46 +37,37 @@ def Find(layerFileName, scenePath=None): the menv layer with the given filename and returns the scene object within it at the given path.''' layer = Layer.Find(layerFileName) - if (scenePath is None): return layer - return layer.GetObjectAtPath(scenePath) + return layer if (scenePath is None) else layer.GetObjectAtPath(scenePath) # Test utilities def _PathElemsToPrefixes(absolute, elements): - if absolute: - string = "/"; - else: - string = "" - + string = "/" if absolute else "" lastElemWasDotDot = False didFirst = False - + for elem in elements: if elem == Path.parentPathElement: # dotdot if didFirst: - string = string + "/" + string = f"{string}/" else: didFirst = True - string = string + elem lastElemWasDotDot = True elif elem[0] == ".": # property if lastElemWasDotDot: - string = string + "/" - string = string + elem + string = f"{string}/" lastElemWasDotDot = False elif elem[0] == "[": - # rel attr or sub-attr indices, don't care which - string = string + elem lastElemWasDotDot = False else: if didFirst: - string = string + "/" + string = f"{string}/" else: didFirst = True - string = string + elem lastElemWasDotDot = False + string = string + elem if not string: return [] path = Path(string) diff --git a/pxr/usd/lib/sdf/sdfGenAsciiParsers.py b/pxr/usd/lib/sdf/sdfGenAsciiParsers.py index ee52d95a639..e10bded0f7d 100644 --- a/pxr/usd/lib/sdf/sdfGenAsciiParsers.py +++ b/pxr/usd/lib/sdf/sdfGenAsciiParsers.py @@ -57,17 +57,20 @@ def _compareFiles(installedFiles, generatedFiles, configuration): diffs = {} for i in xrange(0, len(installedFiles)): - with open(installedFiles[i], 'r') as installedFile,\ - open(generatedFiles[i], 'r') as generatedFile: + with (open(installedFiles[i], 'r') as installedFile, open(generatedFiles[i], 'r') as generatedFile): installedContent = installedFile.read() generatedContent = generatedFile.read() if installedContent != generatedContent: - diff = '\n'.join(unified_diff(installedContent.split('\n'), - generatedContent.split('\n'), - 'Source ' + installedFile.name, - 'Generated ' + generatedFile.name)) + diff = '\n'.join( + unified_diff( + installedContent.split('\n'), + generatedContent.split('\n'), + f'Source {installedFile.name}', + f'Generated {generatedFile.name}', + ) + ) diffs[basename(installedFile.name)] = diff if diffs and failOnDiff: @@ -82,14 +85,14 @@ def _copyGeneratedFiles(installedFiles, generatedFiles, diffs): generatedFiles, installedFiles): if baseName in diffs: - print('Changed: ' + baseName) + print(f'Changed: {baseName}') print(diffs[baseName]) if not access(installedFile, W_OK): - print('Cannot author ' + installedFile + ', (no write access).') + print(f'Cannot author {installedFile}, (no write access).') else: - copyfile(generatedFile, installedFile) + copyfile(generatedFile, installedFile) else: - print('Unchanged: ' + baseName) + print(f'Unchanged: {baseName}') # ----------------------------------------------------------------------------- # Code generation functions. @@ -297,11 +300,16 @@ def _validateSourceDirectory(configuration): bases = configuration[BASES] srcDir = configuration[SRC_DIR] - allFiles = ([join(srcDir, base + '.yy') for base in bases] - + [join(srcDir, base + '.ll') for base in bases] - + [join(srcDir, base + '.tab.cpp') for base in bases] - + [join(srcDir, base + '.tab.h') for base in bases] - + [join(srcDir, base + '.lex.cpp') for base in bases]) + allFiles = ( + ( + ( + [join(srcDir, f'{base}.yy') for base in bases] + + [join(srcDir, f'{base}.ll') for base in bases] + ) + + [join(srcDir, f'{base}.tab.cpp') for base in bases] + ) + + [join(srcDir, f'{base}.tab.h') for base in bases] + ) + [join(srcDir, f'{base}.lex.cpp') for base in bases] if not all(isfile(f) for f in allFiles): exit('*** Invalid source directory. This directory must ' @@ -326,15 +334,23 @@ def _determineBuildSystem(configuration): exit('*** Unable to determine build system.') def _getSconsBuildEnvSetting(environmentVariable, configuration): - command = [find_executable('scons'), '-u', - '-Qq', '--echo=' + environmentVariable] + command = [ + find_executable('scons'), + '-u', + '-Qq', + f'--echo={environmentVariable}', + ] line, _ = Popen(command, stdout=PIPE).communicate() _, envSettingValue = line.strip().split(' = ') if not envSettingValue: - exit('*** Unable to determine ' + environmentVariable + 'from ' - 'SCons build system. Try supplying it through the command line ' - 'options.') + exit( + ( + f'*** Unable to determine {environmentVariable}' + 'from ' + 'SCons build system. Try supplying it through the command line ' + 'options.' + ) + ) return envSettingValue @@ -359,9 +375,13 @@ def _getCMakeBuildEnvSetting(environmentVariable, configuration): _, envSettingValue = line.strip().split('=') if not envSettingValue: - exit('*** Unable to determine ' + environmentVariable + 'from ' - 'CMake build system. Try supplying it through the command line ' - 'options.') + exit( + ( + f'*** Unable to determine {environmentVariable}' + 'from ' + 'CMake build system. Try supplying it through the command line ' + 'options.' + ) + ) return envSettingValue @@ -396,16 +416,16 @@ def _printSection(sectionInfo): _printSection('Canonicalizing generated files') generatedFiles = _canonicalizeFiles(sourceFiles, generatedFiles) - + diffSectionMsg = 'Checking for diffs' if configuration[VALIDATE]: - diffSectionMsg = diffSectionMsg + '(validation on)' + diffSectionMsg += '(validation on)' _printSection(diffSectionMsg) installedFiles = [join(configuration[SRC_DIR], basename(f)) for f in generatedFiles] diffs = _compareFiles(installedFiles, generatedFiles, configuration) - _copyGeneratedFiles(installedFiles, generatedFiles, diffs) + _copyGeneratedFiles(installedFiles, generatedFiles, diffs) # If validation passed, clean up the generated files rmtree(configuration[DEST_DIR]) diff --git a/pxr/usd/lib/sdf/testenv/testSdfCopyUtils.py b/pxr/usd/lib/sdf/testenv/testSdfCopyUtils.py index 2c86c993205..584e1b5429e 100644 --- a/pxr/usd/lib/sdf/testenv/testSdfCopyUtils.py +++ b/pxr/usd/lib/sdf/testenv/testSdfCopyUtils.py @@ -575,9 +575,7 @@ def shouldCopyValue(*args): attrSpecB.default = 2.0 def shouldCopyChildren(*args): - if args[0] == "properties": - return False - return True + return args[0] != "properties" self.assertTrue( Sdf.CopySpec(l, "/Root", l, "/Copy3", @@ -586,13 +584,11 @@ def shouldCopyChildren(*args): dstPrimSpec = l.GetPrimAtPath("/Copy3") self.assertEqual(list(dstPrimSpec.properties), []) - + # Set up a children callback that copies the property named "A" # to a property named "C" under the destination spec. def shouldCopyChildren(*args): - if args[0] == "properties": - return (True, ["A"], ["C"]) - return True + return (True, ["A"], ["C"]) if args[0] == "properties" else True self.assertTrue( Sdf.CopySpec(l, "/Root", l, "/Copy4", diff --git a/pxr/usd/lib/sdf/testenv/testSdfPath2.py b/pxr/usd/lib/sdf/testenv/testSdfPath2.py index a8ef579bd59..2dc133a6dce 100644 --- a/pxr/usd/lib/sdf/testenv/testSdfPath2.py +++ b/pxr/usd/lib/sdf/testenv/testSdfPath2.py @@ -125,7 +125,9 @@ def CheckExpressionPath(path, path2, parentPath, pathStr, pathElems): def CheckOrdering(*args): for i in range(len(args)-1): - assert args[i] < args[i+1], "Expected <%s> to compare less-than <%s>, but it did not"%(args[i], args[i+1]) + assert ( + args[i] < args[i + 1] + ), f"Expected <{args[i]}> to compare less-than <{args[i + 1]}>, but it did not" class TestSdfPath2(unittest.TestCase): def test_Basic(self): diff --git a/pxr/usd/lib/sdf/testenv/testSdfPath2Construct.py b/pxr/usd/lib/sdf/testenv/testSdfPath2Construct.py index b56eca113b6..b6dbd6cb0a0 100644 --- a/pxr/usd/lib/sdf/testenv/testSdfPath2Construct.py +++ b/pxr/usd/lib/sdf/testenv/testSdfPath2Construct.py @@ -257,7 +257,9 @@ def test_GoodPaths(self): def test_BadPaths(self): for str in badPathStrings: - self.assertEqual(Sdf.Path(str), Sdf.Path.emptyPath, "Failed on path str %s"%str) + self.assertEqual( + Sdf.Path(str), Sdf.Path.emptyPath, f"Failed on path str {str}" + ) if __name__ == "__main__": unittest.main() diff --git a/pxr/usd/lib/sdf/testenv/testSdfPayload.py b/pxr/usd/lib/sdf/testenv/testSdfPayload.py index 6e30ebd3aa7..e7ec5a39fd2 100644 --- a/pxr/usd/lib/sdf/testenv/testSdfPayload.py +++ b/pxr/usd/lib/sdf/testenv/testSdfPayload.py @@ -37,11 +37,7 @@ def test_Basic(self): payloads = [] for values in itertools.product(*[a[1] for a in args]): argvalues = zip([a[0] for a in args], values) - kw = {} - for (arg, value) in argvalues: - if value: - kw[arg] = value - + kw = {arg: value for arg, value in argvalues if value} payload = Sdf.Payload(**kw) payloads.append( payload ) diff --git a/pxr/usd/lib/sdf/testenv/testSdfSpecHash.py b/pxr/usd/lib/sdf/testenv/testSdfSpecHash.py index 56a4a2e3329..937b14f7f88 100644 --- a/pxr/usd/lib/sdf/testenv/testSdfSpecHash.py +++ b/pxr/usd/lib/sdf/testenv/testSdfSpecHash.py @@ -27,15 +27,12 @@ class TestSdfSpecHash(unittest.TestCase): def test_Basic(self): - # Test using a python dictionary to associate values with specs. - # This relies on the hash function for spec handles. - test_dict = {} test_value = 'foo' layer = Sdf.Layer.CreateAnonymous() primSpec = Sdf.PrimSpec(layer, "foo", Sdf.SpecifierOver) - test_dict[primSpec] = test_value - for i in range(10): + test_dict = {primSpec: test_value} + for _ in range(10): self.assertEqual(test_dict[ layer.GetObjectAtPath(primSpec.path) ], test_value) diff --git a/pxr/usd/lib/sdf/testenv/testSdfTextReferenceParser.py b/pxr/usd/lib/sdf/testenv/testSdfTextReferenceParser.py index 4be2dc217dc..a9fec375eae 100644 --- a/pxr/usd/lib/sdf/testenv/testSdfTextReferenceParser.py +++ b/pxr/usd/lib/sdf/testenv/testSdfTextReferenceParser.py @@ -57,7 +57,7 @@ def ParseLayer(self, fileName): def test_Parsing(self): for layerName in ('test','test_triple_delim','test_mixed_delim'): - layerFile = layerName + '.sdf' + layerFile = f'{layerName}.sdf' self.assertEqual(self.ParseFile(layerFile), self.ParseLayer(layerFile)) if __name__ == '__main__': diff --git a/pxr/usd/lib/usd/testenv/testUsdAttributeBlocking.py b/pxr/usd/lib/usd/testenv/testUsdAttributeBlocking.py index 10f7c6381bc..22b26e04667 100644 --- a/pxr/usd/lib/usd/testenv/testUsdAttributeBlocking.py +++ b/pxr/usd/lib/usd/testenv/testUsdAttributeBlocking.py @@ -76,14 +76,14 @@ def TestDefaultValueBlocking(sampleAttr, defAttr): formats = [".usda", ".usdc"] for fmt in formats: - stage, defAttr, sampleAttr = CreateTestAssets('test' + fmt) + stage, defAttr, sampleAttr = CreateTestAssets(f'test{fmt}') TestBlock(sampleAttr, defAttr) del stage, defAttr, sampleAttr - stage, defAttr, sampleAttr = CreateTestAssets('test' + fmt) + stage, defAttr, sampleAttr = CreateTestAssets(f'test{fmt}') TestIndividualTimeSampleBlocking(sampleAttr, defAttr) del stage, defAttr, sampleAttr - stage, defAttr, sampleAttr = CreateTestAssets('test' + fmt) + stage, defAttr, sampleAttr = CreateTestAssets(f'test{fmt}') TestDefaultValueBlocking(sampleAttr, defAttr) del stage, defAttr, sampleAttr diff --git a/pxr/usd/lib/usd/testenv/testUsdAttributeConnections.py b/pxr/usd/lib/usd/testenv/testUsdAttributeConnections.py index 35826d64a3b..63995176bac 100644 --- a/pxr/usd/lib/usd/testenv/testUsdAttributeConnections.py +++ b/pxr/usd/lib/usd/testenv/testUsdAttributeConnections.py @@ -25,10 +25,10 @@ import sys, unittest from pxr import Sdf, Tf, Usd -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] def _CreateStage(fmt): - s = Usd.Stage.CreateInMemory('_CreateStage.'+fmt) + s = Usd.Stage.CreateInMemory(f'_CreateStage.{fmt}') s.GetRootLayer().ImportFromString('''#usda 1.0 def Scope "Foo" { @@ -82,48 +82,88 @@ def test_Connections(self): recursive = stage.GetPrimAtPath("/Recursive") self.assertEqual( set(recursive.FindAllAttributeConnectionPaths()), - set([Sdf.Path('/Recursive/A'), Sdf.Path('/Recursive/B'), - Sdf.Path('/Recursive/C'), Sdf.Path('/Recursive/D'), - Sdf.Path('/Recursive/D/A'), Sdf.Path('/Recursive/D/B'), - Sdf.Path('/Recursive/D/C'), Sdf.Path('/Recursive/D/D')])) + { + Sdf.Path('/Recursive/A'), + Sdf.Path('/Recursive/B'), + Sdf.Path('/Recursive/C'), + Sdf.Path('/Recursive/D'), + Sdf.Path('/Recursive/D/A'), + Sdf.Path('/Recursive/D/B'), + Sdf.Path('/Recursive/D/C'), + Sdf.Path('/Recursive/D/D'), + }, + ) self.assertEqual( - set(recursive.FindAllAttributeConnectionPaths( - predicate = - lambda attr: attr.GetPrim().GetName() in ('B', 'D'))), - set([Sdf.Path('/Recursive/A'), Sdf.Path('/Recursive/C'), - Sdf.Path('/Recursive/D/A'), Sdf.Path('/Recursive/D/C')])) + set( + recursive.FindAllAttributeConnectionPaths( + predicate=lambda attr: attr.GetPrim().GetName() in ('B', 'D') + ) + ), + { + Sdf.Path('/Recursive/A'), + Sdf.Path('/Recursive/C'), + Sdf.Path('/Recursive/D/A'), + Sdf.Path('/Recursive/D/C'), + }, + ) self.assertEqual( - set(recursive.FindAllAttributeConnectionPaths( - predicate = - lambda attr: attr.GetPrim().GetName() in ('A', 'C'))), - set([Sdf.Path('/Recursive/B'), Sdf.Path('/Recursive/D'), - Sdf.Path('/Recursive/D/B'), Sdf.Path('/Recursive/D/D')])) - + set( + recursive.FindAllAttributeConnectionPaths( + predicate=lambda attr: attr.GetPrim().GetName() in ('A', 'C') + ) + ), + { + Sdf.Path('/Recursive/B'), + Sdf.Path('/Recursive/D'), + Sdf.Path('/Recursive/D/B'), + Sdf.Path('/Recursive/D/D'), + }, + ) + recursiveA = stage.GetPrimAtPath("/Recursive/A") - self.assertEqual(set(recursiveA.FindAllAttributeConnectionPaths()), - set([Sdf.Path('/Recursive/B')])) - - self.assertEqual(set( - recursiveA.FindAllAttributeConnectionPaths(recurseOnSources=True)), - set([Sdf.Path('/Recursive/A'), Sdf.Path('/Recursive/B'), - Sdf.Path('/Recursive/C'), Sdf.Path('/Recursive/D'), - Sdf.Path('/Recursive/D/A'), Sdf.Path('/Recursive/D/B'), - Sdf.Path('/Recursive/D/C'), Sdf.Path('/Recursive/D/D')])) - - self.assertEqual(set( - recursiveA.FindAllAttributeConnectionPaths( - recurseOnSources=True, - predicate=lambda attr: attr.GetPrim().GetParent().GetName() == - 'Recursive' or attr.GetPrim().GetName() in ('A', 'C'))), - set([Sdf.Path('/Recursive/A'), Sdf.Path('/Recursive/B'), - Sdf.Path('/Recursive/C'), Sdf.Path('/Recursive/D'), - Sdf.Path('/Recursive/D/B'), Sdf.Path('/Recursive/D/D')])) + self.assertEqual( + set(recursiveA.FindAllAttributeConnectionPaths()), + {Sdf.Path('/Recursive/B')}, + ) + + self.assertEqual( + set(recursiveA.FindAllAttributeConnectionPaths(recurseOnSources=True)), + { + Sdf.Path('/Recursive/A'), + Sdf.Path('/Recursive/B'), + Sdf.Path('/Recursive/C'), + Sdf.Path('/Recursive/D'), + Sdf.Path('/Recursive/D/A'), + Sdf.Path('/Recursive/D/B'), + Sdf.Path('/Recursive/D/C'), + Sdf.Path('/Recursive/D/D'), + }, + ) + + self.assertEqual( + set( + recursiveA.FindAllAttributeConnectionPaths( + recurseOnSources=True, + predicate=lambda attr: attr.GetPrim().GetParent().GetName() + == 'Recursive' + or attr.GetPrim().GetName() in ('A', 'C'), + ) + ), + { + Sdf.Path('/Recursive/A'), + Sdf.Path('/Recursive/B'), + Sdf.Path('/Recursive/C'), + Sdf.Path('/Recursive/D'), + Sdf.Path('/Recursive/D/B'), + Sdf.Path('/Recursive/D/D'), + }, + ) def test_ConnectionsInInstances(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestConnectionsInInstances.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestConnectionsInInstances.{fmt}') s.GetRootLayer().ImportFromString('''#usda 1.0 def Scope "Ref" { @@ -177,8 +217,7 @@ def Scope "Root" ( def test_ConnectionsToObjectsInInstances(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory( - 'TestConnectionsToObjectsInInstances.'+fmt) + stage = Usd.Stage.CreateInMemory(f'TestConnectionsToObjectsInInstances.{fmt}') stage.GetRootLayer().ImportFromString('''#usda 1.0 def "Instance" { @@ -376,7 +415,7 @@ def _TestConnectionInMaster(attr): def test_AuthoringConnections(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory("testAuthoringConnections." + fmt) + stage = Usd.Stage.CreateInMemory(f"testAuthoringConnections.{fmt}") prim = stage.DefinePrim("/Test") attr = prim.CreateAttribute("attr", Sdf.ValueTypeNames.Int) @@ -438,8 +477,7 @@ def test_AuthoringConnections(self): def test_ConnectionsWithInconsistentSpecs(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory( - 'TestConnectionsWithInconsistentSpecs.'+fmt) + stage = Usd.Stage.CreateInMemory(f'TestConnectionsWithInconsistentSpecs.{fmt}') stage.GetRootLayer().ImportFromString('''#usda 1.0 def "A" { diff --git a/pxr/usd/lib/usd/testenv/testUsdBug119633.py b/pxr/usd/lib/usd/testenv/testUsdBug119633.py index 2aa6c59166f..7d038d80e19 100644 --- a/pxr/usd/lib/usd/testenv/testUsdBug119633.py +++ b/pxr/usd/lib/usd/testenv/testUsdBug119633.py @@ -29,7 +29,7 @@ def TestBug119633(): layerFile = 'root.usda' try: stage = Usd.Stage.Open(layerFile) - assert stage, 'failed to create stage for %s' % layerFile + assert stage, f'failed to create stage for {layerFile}' prim = stage.GetPrimAtPath('/SardineGroup_OceanA') assert prim, 'failed to find prim /World' except Tf.ErrorException: diff --git a/pxr/usd/lib/usd/testenv/testUsdBugs.py b/pxr/usd/lib/usd/testenv/testUsdBugs.py index c0acf754fd5..3be5bb13d34 100644 --- a/pxr/usd/lib/usd/testenv/testUsdBugs.py +++ b/pxr/usd/lib/usd/testenv/testUsdBugs.py @@ -96,31 +96,46 @@ def test_155392(self): s = Usd.Stage.Open(l1, Usd.Stage.LoadAll) self.assertTrue( - all([x.IsLoaded() for x in [ - s.GetPrimAtPath('/p1'), - s.GetPrimAtPath('/p1/y'), - s.GetPrimAtPath('/p2'), - s.GetPrimAtPath('/p2/y')]])) + all( + x.IsLoaded() + for x in [ + s.GetPrimAtPath('/p1'), + s.GetPrimAtPath('/p1/y'), + s.GetPrimAtPath('/p2'), + s.GetPrimAtPath('/p2/y'), + ] + ) + ) # Now uninstance, and assert that load state is preserved. s.GetPrimAtPath('/p2').SetInstanceable(False) self.assertTrue( - all([x.IsLoaded() for x in [ - s.GetPrimAtPath('/p1'), - s.GetPrimAtPath('/p1/y'), - s.GetPrimAtPath('/p2'), - s.GetPrimAtPath('/p2/y')]])) + all( + x.IsLoaded() + for x in [ + s.GetPrimAtPath('/p1'), + s.GetPrimAtPath('/p1/y'), + s.GetPrimAtPath('/p2'), + s.GetPrimAtPath('/p2/y'), + ] + ) + ) # Reinstance /p2 for next test. s.GetPrimAtPath('/p2').SetInstanceable(True) self.assertTrue( - all([x.IsLoaded() for x in [ - s.GetPrimAtPath('/p1'), - s.GetPrimAtPath('/p1/y'), - s.GetPrimAtPath('/p2'), - s.GetPrimAtPath('/p2/y')]])) + all( + x.IsLoaded() + for x in [ + s.GetPrimAtPath('/p1'), + s.GetPrimAtPath('/p1/y'), + s.GetPrimAtPath('/p2'), + s.GetPrimAtPath('/p2/y'), + ] + ) + ) # Now do the same but nested-instance everything. l3 = Sdf.Layer.CreateAnonymous('.usda') @@ -145,40 +160,52 @@ def test_155392(self): s2 = Usd.Stage.Open(l3, Usd.Stage.LoadAll) self.assertTrue( - all([x.IsLoaded() for x in [ - s2.GetPrimAtPath('/i1'), - s2.GetPrimAtPath('/i1/c'), - s2.GetPrimAtPath('/i1/c/y'), - s2.GetPrimAtPath('/i2'), - s2.GetPrimAtPath('/i2/c'), - s2.GetPrimAtPath('/i2/c/y') - ]])) + all( + x.IsLoaded() + for x in [ + s2.GetPrimAtPath('/i1'), + s2.GetPrimAtPath('/i1/c'), + s2.GetPrimAtPath('/i1/c/y'), + s2.GetPrimAtPath('/i2'), + s2.GetPrimAtPath('/i2/c'), + s2.GetPrimAtPath('/i2/c/y'), + ] + ) + ) # Uninstance outer. s2.GetPrimAtPath('/i1').SetInstanceable(False) - + self.assertTrue( - all([x.IsLoaded() for x in [ - s2.GetPrimAtPath('/i1'), - s2.GetPrimAtPath('/i1/c'), - s2.GetPrimAtPath('/i1/c/y'), - s2.GetPrimAtPath('/i2'), - s2.GetPrimAtPath('/i2/c'), - s2.GetPrimAtPath('/i2/c/y') - ]])) + all( + x.IsLoaded() + for x in [ + s2.GetPrimAtPath('/i1'), + s2.GetPrimAtPath('/i1/c'), + s2.GetPrimAtPath('/i1/c/y'), + s2.GetPrimAtPath('/i2'), + s2.GetPrimAtPath('/i2/c'), + s2.GetPrimAtPath('/i2/c/y'), + ] + ) + ) # Uninstance inner. s2.GetPrimAtPath('/i1/c').SetInstanceable(False) self.assertTrue( - all([x.IsLoaded() for x in [ - s2.GetPrimAtPath('/i1'), - s2.GetPrimAtPath('/i1/c'), - s2.GetPrimAtPath('/i1/c/y'), - s2.GetPrimAtPath('/i2'), - s2.GetPrimAtPath('/i2/c'), - s2.GetPrimAtPath('/i2/c/y') - ]])) + all( + x.IsLoaded() + for x in [ + s2.GetPrimAtPath('/i1'), + s2.GetPrimAtPath('/i1/c'), + s2.GetPrimAtPath('/i1/c/y'), + s2.GetPrimAtPath('/i2'), + s2.GetPrimAtPath('/i2/c'), + s2.GetPrimAtPath('/i2/c/y'), + ] + ) + ) def test_156222(self): from pxr import Sdf, Usd @@ -192,8 +219,9 @@ def test_156222(self): # The bug is non-deterministic because of threaded composition, # but it's easier to reproduce with more instance prims. numInstancePrims = 50 - instancePrimPaths = [Sdf.Path('/Instance_{}'.format(i)) - for i in xrange(numInstancePrims)] + instancePrimPaths = [ + Sdf.Path(f'/Instance_{i}') for i in xrange(numInstancePrims) + ] for path in instancePrimPaths: instancePrim = Sdf.CreatePrimInLayer(l, path) instancePrim.instanceable = True diff --git a/pxr/usd/lib/usd/testenv/testUsdClasses.py b/pxr/usd/lib/usd/testenv/testUsdClasses.py index d633963f240..4ff646bfe66 100644 --- a/pxr/usd/lib/usd/testenv/testUsdClasses.py +++ b/pxr/usd/lib/usd/testenv/testUsdClasses.py @@ -25,12 +25,12 @@ from pxr import Sdf, Usd, Tf import unittest -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] class TestUsdClasses(unittest.TestCase): def test_Basic(self): for fmt in allFormats: - l = Sdf.Layer.CreateAnonymous('BasicClassTest.'+fmt) + l = Sdf.Layer.CreateAnonymous(f'BasicClassTest.{fmt}') stage = Usd.Stage.Open(l.identifier) diff --git a/pxr/usd/lib/usd/testenv/testUsdCollectionAPI.py b/pxr/usd/lib/usd/testenv/testUsdCollectionAPI.py index 76be4780857..63c0eef25ad 100644 --- a/pxr/usd/lib/usd/testenv/testUsdCollectionAPI.py +++ b/pxr/usd/lib/usd/testenv/testUsdCollectionAPI.py @@ -50,7 +50,6 @@ class TestUsdCollectionAPI(unittest.TestCase): def tearDown(self): # Discard any edits made to layers stage.Reload() - pass def test_AuthorCollections(self): # ---------------------------------------------------------- @@ -424,10 +423,10 @@ def test_CollectionEquivalence(self): else: self.assertNotEqual(mqueries[i], mqueries[j]) - # Confirm that the hash operator lets us use python dicts - mqueryToPath = {} - for (coll,mquery) in zip(collections, mqueries): - mqueryToPath[mquery] = coll.GetCollectionPath() + mqueryToPath = { + mquery: coll.GetCollectionPath() + for coll, mquery in zip(collections, mqueries) + } self.assertEqual(len(mqueryToPath.keys()), len(mqueries)) if __name__ == "__main__": diff --git a/pxr/usd/lib/usd/testenv/testUsdCreateProperties.py b/pxr/usd/lib/usd/testenv/testUsdCreateProperties.py index 29ca3f8efdb..8f7233142f1 100644 --- a/pxr/usd/lib/usd/testenv/testUsdCreateProperties.py +++ b/pxr/usd/lib/usd/testenv/testUsdCreateProperties.py @@ -25,7 +25,7 @@ import sys, os, unittest from pxr import Usd, Sdf, Gf, Tf -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] def _AssertTrue(test, errorMessage): if not test: @@ -50,29 +50,27 @@ def test_Basic(self): # Parameters prim = "/Foo" prop = "Something" - propPath = prim + "." + prop + propPath = f"{prim}.{prop}" value = Gf.Vec3f(1.0, 2.0, 3.0) for fmt in allFormats: # Setup a new stage - layer = _CreateLayer("foo."+fmt) + layer = _CreateLayer(f"foo.{fmt}") stage = Usd.Stage.Open(layer.identifier) # This ensures incremental recomposition will pickup newly created prims - _AssertFalse(stage.GetPrimAtPath(prim), - "Prim already exists at " + prim) + _AssertFalse(stage.GetPrimAtPath(prim), f"Prim already exists at {prim}") stage.OverridePrim(prim) - _AssertTrue(stage.GetPrimAtPath(prim), - "Failed to create prim at " + prim) + _AssertTrue(stage.GetPrimAtPath(prim), f"Failed to create prim at {prim}") p = stage.GetPrimAtPath(prim) - _AssertTrue(not p.GetAttribute(prop), - "Attribute already exists at " + propPath) + _AssertTrue( + not p.GetAttribute(prop), f"Attribute already exists at {propPath}" + ) p.CreateAttribute(prop, Sdf.ValueTypeNames.String) - _AssertTrue(p.GetAttribute(prop), - "Failed to create attribute at " + propPath) + _AssertTrue(p.GetAttribute(prop), f"Failed to create attribute at {propPath}") # # Verify default parameters are set as expected @@ -113,8 +111,8 @@ def test_ImplicitSpecCreation(self): # # Setup layers, stage, prims, attributes and relationships. # - weakLayer = _CreateLayer("SpecCreationTest_weak."+fmt) - strongLayer = _CreateLayer("SpecCreationTest_strong."+fmt) + weakLayer = _CreateLayer(f"SpecCreationTest_weak.{fmt}") + strongLayer = _CreateLayer(f"SpecCreationTest_strong.{fmt}") stage = Usd.Stage.Open(weakLayer.identifier); p = stage.OverridePrim("/Parent/Nested/Child") @@ -169,25 +167,27 @@ def test_ImplicitSpecCreation(self): # # Now, we should be able to set /Parent/Nested/Child.attr in the weaker # layer. - # + # _AssertTrue( strongPrim.GetAttribute("attr1").Set("anyStringValue", 1.0), - "Expected to be able to Set <" + str(strongPrim.GetPath()) - + ".attr1>, but failed.") + f"Expected to be able to Set <{str(strongPrim.GetPath())}.attr1>, but failed.", + ) _AssertTrue( strongPrim.GetAttribute("attr2").SetMetadata( - "documentation", "worked!"), - "Expected to be able to SetMetadata <" + str(strongPrim.GetPath()) - + ".attr2>, but failed.") + "documentation", "worked!" + ), + f"Expected to be able to SetMetadata <{str(strongPrim.GetPath())}.attr2>, but failed.", + ) _AssertTrue( strongPrim.GetRelationship("rel1").AddTarget("/Foo/Bar"), - "Expected to be able to AppendTarget to <" + str(strongPrim.GetPath()) - + ".rel1>, but failed.") + f"Expected to be able to AppendTarget to <{str(strongPrim.GetPath())}.rel1>, but failed.", + ) _AssertTrue( strongPrim.GetRelationship("rel2").SetMetadata( - "documentation", "rel worked!"), - "Expected to be able to AppendTarget to <" + str(strongPrim.GetPath()) - + ".rel2>, but failed.") + "documentation", "rel worked!" + ), + f"Expected to be able to AppendTarget to <{str(strongPrim.GetPath())}.rel2>, but failed.", + ) # # Finally, attempt to create a new attribute & relationship on a spec in @@ -222,8 +222,8 @@ def test_ImplicitSpecCreation(self): def test_IsDefined(self): for fmt in allFormats: - weakLayer = _CreateLayer("IsDefined_weak."+fmt) - strongLayer = _CreateLayer("IsDefined_strong."+fmt) + weakLayer = _CreateLayer(f"IsDefined_weak.{fmt}") + strongLayer = _CreateLayer(f"IsDefined_strong.{fmt}") stage = Usd.Stage.Open(weakLayer.identifier); p = stage.OverridePrim("/Parent") @@ -253,11 +253,11 @@ def test_IsDefined(self): def test_HasValue(self): for fmt in allFormats: - tag = 'foo.'+fmt + tag = f'foo.{fmt}' s = Usd.Stage.CreateInMemory(tag) p = s.OverridePrim("/SomePrim") p.CreateAttribute("myAttr", Sdf.ValueTypeNames.String) - + attr = p.GetAttribute("myAttr") assert not attr.HasValue() assert not attr.HasAuthoredValueOpinion() @@ -277,7 +277,7 @@ def test_HasValue(self): attr.ClearAtTime(1.0) assert not attr.HasValue() assert not attr.HasAuthoredValueOpinion() - + attr.Set("val", 1.0) assert attr.HasValue() assert attr.HasAuthoredValueOpinion() @@ -308,7 +308,7 @@ def test_GetSetNumpy(self): return for fmt in allFormats: - s = Usd.Stage.CreateInMemory('GetSetNumpyTest.'+fmt) + s = Usd.Stage.CreateInMemory(f'GetSetNumpyTest.{fmt}') prim = s.OverridePrim('/test') prim.CreateAttribute('extent', Sdf.ValueTypeNames.Float3Array) @@ -328,7 +328,7 @@ def test_GetSetNumpy(self): def test_SetArraysWithLists(self): from pxr import Vt, Sdf for fmt in allFormats: - s = Usd.Stage.CreateInMemory('SetArraysWithListsTest.'+fmt) + s = Usd.Stage.CreateInMemory(f'SetArraysWithListsTest.{fmt}') prim = s.OverridePrim('/test') strs = prim.CreateAttribute('strs', Sdf.ValueTypeNames.StringArray) toks = prim.CreateAttribute('toks', Sdf.ValueTypeNames.TokenArray) @@ -425,7 +425,7 @@ def test_Downcast(self): # Check that wrapped API returning UsdProperty actually produces # UsdAttribute and UsdRelationship instances. for fmt in allFormats: - s = Usd.Stage.CreateInMemory('tag.'+fmt) + s = Usd.Stage.CreateInMemory(f'tag.{fmt}') p = s.DefinePrim('/p') a = p.CreateAttribute('a', Sdf.ValueTypeNames.Float) r = p.CreateRelationship('r') @@ -514,14 +514,14 @@ def test_GetPropertyStack(self): # Test basic overs for fmt in allFormats: - layerA = _CreateLayer('layerA.'+fmt) - layerB = _CreateLayer('layerB.'+fmt) - layerC = _CreateLayer('layerC.'+fmt) + layerA = _CreateLayer(f'layerA.{fmt}') + layerB = _CreateLayer(f'layerB.{fmt}') + layerC = _CreateLayer(f'layerC.{fmt}') stage = Usd.Stage.Open(layerA.identifier) prim = stage.DefinePrim(primPath) prim.CreateAttribute(propName, Sdf.ValueTypeNames.String) - + stage = Usd.Stage.Open(layerB.identifier) over = stage.OverridePrim(primPath) over.CreateAttribute(propName, Sdf.ValueTypeNames.String) @@ -546,12 +546,12 @@ def test_GetPropertyStack(self): def test_GetPropertyStackWithClips(self): clipPath = '/root/fx/test' attrName = 'extent' - fullPath = clipPath + '.' + attrName + fullPath = f'{clipPath}.{attrName}' for fmt in allFormats: - clipA = Sdf.Layer.CreateNew('clipA.'+fmt) - clipB = Sdf.Layer.CreateNew('clipB.'+fmt) - clipC = Sdf.Layer.CreateNew('clipC.'+fmt) + clipA = Sdf.Layer.CreateNew(f'clipA.{fmt}') + clipB = Sdf.Layer.CreateNew(f'clipB.{fmt}') + clipC = Sdf.Layer.CreateNew(f'clipC.{fmt}') clips = [clipA, clipB, clipC] clipTime = 102.0 @@ -565,19 +565,19 @@ def test_GetPropertyStackWithClips(self): stage.SetEndTimeCode(clipTime) # Generate our necessary topology layer - topologyLayer = Sdf.Layer.CreateNew('root.topology.'+fmt) + topologyLayer = Sdf.Layer.CreateNew(f'root.topology.{fmt}') stage = Usd.Stage.Open(topologyLayer) prim = stage.DefinePrim(clipPath) prim.CreateAttribute(attrName, Sdf.ValueTypeNames.Double) # Generate our necessary clip metadata - root = Sdf.Layer.CreateNew('root.'+fmt) + root = Sdf.Layer.CreateNew(f'root.{fmt}') stage = Usd.Stage.Open(root) prim = stage.DefinePrim(clipPath) clipPrim = Usd.ClipsAPI(prim) clipPrim.SetClipAssetPaths([Sdf.AssetPath(c.identifier) for c in clips]) clipPrim.SetClipPrimPath(clipPath) - clipPrim.SetClipManifestAssetPath('root.topology.'+fmt) + clipPrim.SetClipManifestAssetPath(f'root.topology.{fmt}') # Add a reference to our topology layer rootPath = Sdf.Path('/root') @@ -587,7 +587,7 @@ def test_GetPropertyStackWithClips(self): clipTime = 102.0 stageTime = 0.0 - for c in clips: + for _ in clips: currentClipActive = list(clipPrim.GetClipActive()) currentClipActive.append( [clipTime, stageTime] ) clipPrim.SetClipActive(currentClipActive) @@ -602,21 +602,17 @@ def test_GetPropertyStackWithClips(self): stage = Usd.Stage.Open(root.identifier) prim = stage.GetPrimAtPath(clipPath) attr = prim.GetAttribute(attrName) - + # Ensure we only pick up relevant clips # In the case of a default time code we don't want any of the # value clips to show up in our stack of properties stack = attr.GetPropertyStack(Usd.TimeCode.Default()) self.assertEqual(stack, [topologyLayer.GetPropertyAtPath(fullPath)]) - # ensure that clip 'c' is in the result when the time code - # being used is exactly on 'c's endpoints - clipTime = 102 - for i in xrange(0, len(clips)): + for clipTime, i in enumerate(xrange(0, len(clips)), start=102): stack = attr.GetPropertyStack(clipTime) self.assertEqual(stack, [clips[i].GetPropertyAtPath(fullPath), topologyLayer.GetPropertyAtPath(fullPath)]) - clipTime += 1 if __name__ == "__main__": unittest.main() diff --git a/pxr/usd/lib/usd/testenv/testUsdDataFormats.py b/pxr/usd/lib/usd/testenv/testUsdDataFormats.py index 8930884e4d6..81a75314d12 100644 --- a/pxr/usd/lib/usd/testenv/testUsdDataFormats.py +++ b/pxr/usd/lib/usd/testenv/testUsdDataFormats.py @@ -31,10 +31,11 @@ class TestUsdDataFormats(unittest.TestCase): def test_PseudoRoot(self): """Verify that pseudoroots report that they does not have specifiers with all file formats""" for fmt in allFormats: - layer = Sdf.Layer.CreateAnonymous('pseudoroot.' + fmt) - assert layer, 'Could not create ' + fmt + ' layer' - assert not layer.pseudoRoot.HasInfo('specifier'), \ - fmt + ' layer reports unexpected pseudoroot specifier' + layer = Sdf.Layer.CreateAnonymous(f'pseudoroot.{fmt}') + assert layer, f'Could not create {fmt} layer' + assert not layer.pseudoRoot.HasInfo( + 'specifier' + ), f'{fmt} layer reports unexpected pseudoroot specifier' prim = Sdf.PrimSpec(layer, 'root', Sdf.SpecifierDef) assert prim assert prim.HasInfo('specifier') @@ -63,7 +64,7 @@ def test_AssetPath(self): """ from pxr import Usd for fmt in allFormats: - s = Usd.Stage.CreateNew('test.' + fmt) + s = Usd.Stage.CreateNew(f'test.{fmt}') p = s.DefinePrim("/X", 'Scope') p.SetCustomDataByKey('identifier', Sdf.AssetPath('asset.usd')) self.assertEqual(p.GetCustomDataByKey('identifier'), diff --git a/pxr/usd/lib/usd/testenv/testUsdEditTarget.py b/pxr/usd/lib/usd/testenv/testUsdEditTarget.py index 525b8752fd4..f0169658a70 100644 --- a/pxr/usd/lib/usd/testenv/testUsdEditTarget.py +++ b/pxr/usd/lib/usd/testenv/testUsdEditTarget.py @@ -32,7 +32,7 @@ def test_PathTranslationAndValueResolution(self): layer = Sdf.Layer.FindOrOpen(layerFile) assert layer, 'failed to find "test.usda' stage = Usd.Stage.Open(layerFile) - assert stage, 'failed to create stage for %s' % layerFile + assert stage, f'failed to create stage for {layerFile}' prim = stage.GetPrimAtPath('/Sarah') assert prim, 'failed to find prim /Sarah' @@ -65,8 +65,10 @@ def MakeEditTarget(node): def CheckPath(target, scenePath, specPath): result = target.MapToSpecPath(scenePath) if result != specPath: - raise AssertionError, '%s -> %s, expected %s -> %s' % ( - scenePath, result, scenePath, specPath) + raise ( + AssertionError, + f'{scenePath} -> {result}, expected {scenePath} -> {specPath}', + ) CheckPath(Sarah, '/Sarah', '/Sarah') CheckPath(Sarah, '/Sarah/child', '/Sarah/child') @@ -111,56 +113,29 @@ def CheckPath(target, scenePath, specPath): ######################################################################## return ######################################################################## - # XXX ! The following portion of this test is disabled since Usd has no API - # for composing up to some point. This should be reenabled when that's - # available. - - # Test value resolution across reference, inherit, and variant. - def CheckValue(obj, key, target, expected): - result = obj.ComposeInfo( - key, defVal=None, editTarget=target, - excerptType=Csd.ExcerptTypeAll, composeInfo=None) - if not Gf.IsClose(result, expected, 1e-4): - raise AssertionError, ("Got '%s' resolving '%s' on '%s', expected " - "'%s'" % (result, key, obj.path, expected)) - - displayColor = scene.GetObjectAtPath('/Sarah.displayColor') - - CheckValue(displayColor, 'default', Sarah, - Gf.Vec3d(0.1, 0.2, 0.3)) - CheckValue(displayColor, 'default', class_Sarah, - Gf.Vec3d(1, 1, 1)) - CheckValue(displayColor, 'default', Sarah_displayColor_red, - Gf.Vec3d(1, 0, 0)) - CheckValue(displayColor, 'default', Sarah_Defaults, - Gf.Vec3d(0, 0, 1)) - CheckValue(displayColor, 'default', Sarah_Base, - Gf.Vec3d(0.8, 0, 0)) - CheckValue(displayColor, 'default', Sarah_Base_displayColor_red, - Gf.Vec3d(0.8, 0, 0)) - ######################################################################## def test_StageEditTargetAPI(self): def OpenLayer(name): - fullName = '%s.usda' % name + fullName = f'{name}.usda' layer = Sdf.Layer.FindOrOpen(fullName) - assert layer, 'failed to open layer @%s@' % fullName + assert layer, f'failed to open layer @{fullName}@' return layer # Open stage. layer = OpenLayer('testAPI_root') stage = Usd.Stage.Open(layer.identifier) - assert stage, 'failed to create stage for @%s@' % layer.identifier + assert stage, f'failed to create stage for @{layer.identifier}@' # Check GetLayerStack behavior. assert stage.GetLayerStack()[0] == stage.GetSessionLayer() # Get LayerStack without session layer. rootLayer, subLayer1, subLayer2 = \ - stage.GetLayerStack(includeSessionLayers=False) - assert subLayer1 and subLayer2, ('expected @%s@ to have 2 sublayers' % - layer.identifier) + stage.GetLayerStack(includeSessionLayers=False) + assert ( + subLayer1 and subLayer2 + ), f'expected @{layer.identifier}@ to have 2 sublayers' assert rootLayer == stage.GetRootLayer() # Get Sarah prim. @@ -185,7 +160,7 @@ def OpenLayer(name): stage.SetEditTarget(stage.GetRootLayer()) assert stage.GetEditTarget() == stage.GetRootLayer(), \ - 'failed to set EditTarget' + 'failed to set EditTarget' # Try authoring to sublayers using context object. with Usd.EditContext(stage, subLayer2): @@ -197,7 +172,7 @@ def OpenLayer(name): # Target should be back to root layer. assert stage.GetEditTarget() == stage.GetRootLayer(), \ - 'EditContext failed to restore EditTarget' + 'EditContext failed to restore EditTarget' # Set to subLayer1. stage.SetEditTarget(subLayer1) @@ -216,7 +191,7 @@ def OpenLayer(name): # Target should be back to subLayer1. assert stage.GetEditTarget() == subLayer1, \ - 'EditContext failed to restore EditTarget' + 'EditContext failed to restore EditTarget' # Verify an error is reported for setting EditTarget as a local layer # that's not in the local LayerStack. @@ -230,7 +205,7 @@ def test_StageEditTargetSessionSublayer(self): usdFile = 'testSessionSublayerEditTarget.usda' stage = Usd.Stage.Open(usdFile) - assert stage, 'failed to create stage for @%s@' % usdFile + assert stage, f'failed to create stage for @{usdFile}@' sessionLayer = stage.GetSessionLayer() assert len(sessionLayer.subLayerPaths) == 0 diff --git a/pxr/usd/lib/usd/testenv/testUsdFileFormats.py b/pxr/usd/lib/usd/testenv/testUsdFileFormats.py index 6dd6243c35f..ac77b52dfee 100644 --- a/pxr/usd/lib/usd/testenv/testUsdFileFormats.py +++ b/pxr/usd/lib/usd/testenv/testUsdFileFormats.py @@ -45,10 +45,10 @@ def VerifyUsdFileFormat(usdFileName, underlyingFormatId): # Copy the file to a temporary location and replace the extension with # the expected format, then try to open it. import tempfile - (tmpFile, tmpFileName) = \ - tempfile.mkstemp( - prefix=os.path.splitext(os.path.basename(usdFileName))[0], - suffix='.' + underlyingFormatId) + (tmpFile, tmpFileName) = tempfile.mkstemp( + prefix=os.path.splitext(os.path.basename(usdFileName))[0], + suffix=f'.{underlyingFormatId}', + ) os.close(tmpFile) shutil.copyfile(usdFileName, tmpFileName) @@ -122,7 +122,7 @@ def test_UsdLayerSave(self): # Verify that opening a .usd file, authoring changes, and saving it # maintains the same underlying file format. def _TestLayerOpenAndSave(srcFilename, expectedFileFormat): - dstFilename = 'testUsdLayerSave_%s.usd' % expectedFileFormat + dstFilename = f'testUsdLayerSave_{expectedFileFormat}.usd' shutil.copyfile(srcFilename, dstFilename) layer = Sdf.Layer.FindOrOpen(dstFilename) self.assertEqual(GetUnderlyingUsdFileFormat(layer), expectedFileFormat) diff --git a/pxr/usd/lib/usd/testenv/testUsdFlatten.py b/pxr/usd/lib/usd/testenv/testUsdFlatten.py index 52a5451a07f..9d7aade64c7 100644 --- a/pxr/usd/lib/usd/testenv/testUsdFlatten.py +++ b/pxr/usd/lib/usd/testenv/testUsdFlatten.py @@ -60,9 +60,11 @@ def _CompareMetadata(composed, flat, indent): continue print (" " * indent) + ":",cKey - assert cKey in fdata, str(composed.GetPath()) + " : " + cKey - assert composed.GetMetadata(cKey) == flat.GetMetadata(cKey), "GetMetadata -- " + str(composed.GetPath()) + " : " + cKey - assert cdata[cKey] == fdata[cKey], str(composed.GetPath()) + " : " + cKey + assert cKey in fdata, f"{str(composed.GetPath())} : {cKey}" + assert composed.GetMetadata(cKey) == flat.GetMetadata( + cKey + ), f"GetMetadata -- {str(composed.GetPath())} : {cKey}" + assert cdata[cKey] == fdata[cKey], f"{str(composed.GetPath())} : {cKey}" class TestUsdFlatten(unittest.TestCase): def test_Flatten(self): @@ -195,7 +197,7 @@ def test_FlattenAttributeWithUnregisteredType(self): def test_FlattenRelationshipTargets(self): basePath = 'relationshipTargets/' - stageFile = basePath+'source.usda' + stageFile = f'{basePath}source.usda' stage = Usd.Stage.Open(stageFile) assert stage @@ -205,7 +207,7 @@ def test_FlattenRelationshipTargets(self): assert rel self.assertEqual(rel.GetTargets(), [Sdf.Path('/bar/baz')]) - resultFile = basePath+'result.usda' + resultFile = f'{basePath}result.usda' stage.Export(resultFile) resultStage = Usd.Stage.Open(resultFile) @@ -219,13 +221,13 @@ def test_FlattenRelationshipTargets(self): def test_FlattenConnections(self): basePath = 'connections/' - stageFile = basePath+'source.usda' + stageFile = f'{basePath}source.usda' stage = Usd.Stage.Open(stageFile) assert stage barPrim = stage.GetPrimAtPath('/bar') assert barPrim - + fooAttr = barPrim.GetAttribute('foo') assert fooAttr self.assertEqual(fooAttr.GetConnections(), [Sdf.Path('/bar/baz.foo')]) @@ -236,7 +238,7 @@ def test_FlattenConnections(self): assert basAttr self.assertEqual(basAttr.GetConnections(), [Sdf.Path('/bar.bas')]) - resultFile = basePath+'result.usda' + resultFile = f'{basePath}result.usda' stage.Export(resultFile) resultStage = Usd.Stage.Open(resultFile) @@ -293,21 +295,22 @@ def test_FlattenAssetPaths(self): # All asset paths in the flattened result should be anchored, # even though the asset being referred to does not exist. attr = resultLayer.GetAttributeAtPath("/AssetPathTest.assetPath") - + timeSamples = attr.GetInfo("timeSamples") self.assertEqual(os.path.normpath(timeSamples[0].path), os.path.abspath("assetPaths/asset.usda")) self.assertEqual(os.path.normpath(timeSamples[1].path), os.path.abspath("assetPaths/asset.usda")) - + self.assertEqual( os.path.normpath(attr.GetInfo("default").path), os.path.abspath("assetPaths/asset.usda")) - + attr = resultLayer.GetAttributeAtPath("/AssetPathTest.assetPathArray") self.assertEqual( - list([os.path.normpath(p.path) for p in attr.GetInfo("default")]), - [os.path.abspath("assetPaths/asset.usda")]) + [os.path.normpath(p.path) for p in attr.GetInfo("default")], + [os.path.abspath("assetPaths/asset.usda")], + ) prim = resultLayer.GetPrimAtPath("/AssetPathTest") metadataDict = prim.GetInfo("customData") @@ -315,18 +318,18 @@ def test_FlattenAssetPaths(self): os.path.normpath(metadataDict["assetPath"].path), os.path.abspath("assetPaths/asset.usda")) self.assertEqual( - list([os.path.normpath(p.path) - for p in metadataDict["assetPathArray"]]), - [os.path.abspath("assetPaths/asset.usda")]) - + [os.path.normpath(p.path) for p in metadataDict["assetPathArray"]], + [os.path.abspath("assetPaths/asset.usda")], + ) + metadataDict = metadataDict["subDict"] self.assertEqual( os.path.normpath(metadataDict["assetPath"].path), os.path.abspath("assetPaths/asset.usda")) self.assertEqual( - list([os.path.normpath(p.path) - for p in metadataDict["assetPathArray"]]), - [os.path.abspath("assetPaths/asset.usda")]) + [os.path.normpath(p.path) for p in metadataDict["assetPathArray"]], + [os.path.abspath("assetPaths/asset.usda")], + ) if __name__ == "__main__": diff --git a/pxr/usd/lib/usd/testenv/testUsdFlattenProperties.py b/pxr/usd/lib/usd/testenv/testUsdFlattenProperties.py index 7381c918c34..12267ae6a14 100644 --- a/pxr/usd/lib/usd/testenv/testUsdFlattenProperties.py +++ b/pxr/usd/lib/usd/testenv/testUsdFlattenProperties.py @@ -133,7 +133,7 @@ def test_FlattenWithOffsets(self): """Tests that layer offsets are taken into account when flattening attribute time samples.""" srcAttr = self.stage.GetPrimAtPath("/OffsetTimeSamples") \ - .GetAttribute("a") + .GetAttribute("a") if Usd.UsesInverseLayerOffset(): self.assertEqual(self._GetTimeSamples(srcAttr), @@ -159,26 +159,23 @@ def test_FlattenWithOffsets(self): self._GetTimeSamplesInLayer( self.rootLayer, "/OffsetTimeSamplesRoot.a"), { 10: 100, 20: 1000 }) - + with Usd.EditContext( - self.stage, self.stage.GetEditTargetForLocalLayer(self.subLayer)): + self.stage, self.stage.GetEditTargetForLocalLayer(self.subLayer)): dstAttr = srcAttr.FlattenTo( self.stage.OverridePrim("/OffsetTimeSamplesSublayer")) - + if Usd.UsesInverseLayerOffset(): self.assertEqual( self._GetTimeSamples(dstAttr), { -10: 100, 0: 1000 }) - self.assertEqual( - self._GetTimeSamplesInLayer( - self.subLayer, "/OffsetTimeSamplesSublayer.a"), - { 0: 100, 10: 1000 }) else: self.assertEqual( self._GetTimeSamples(dstAttr), { 10: 100, 20: 1000 }) - self.assertEqual( - self._GetTimeSamplesInLayer( - self.subLayer, "/OffsetTimeSamplesSublayer.a"), - { 0: 100, 10: 1000 }) + + self.assertEqual( + self._GetTimeSamplesInLayer( + self.subLayer, "/OffsetTimeSamplesSublayer.a"), + { 0: 100, 10: 1000 }) def test_DefaultAndTimeSamples(self): """Tests that properties with both a default value and time samples diff --git a/pxr/usd/lib/usd/testenv/testUsdInherits.py b/pxr/usd/lib/usd/testenv/testUsdInherits.py index fd68063300d..30cd98baf0b 100644 --- a/pxr/usd/lib/usd/testenv/testUsdInherits.py +++ b/pxr/usd/lib/usd/testenv/testUsdInherits.py @@ -25,12 +25,12 @@ import unittest from pxr import Usd, Pcp, Sdf, Tf -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] class TestUsdInherits(unittest.TestCase): def test_BasicApi(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory("x."+fmt) + stage = Usd.Stage.CreateInMemory(f"x.{fmt}") classA = stage.CreateClassPrim("/ClassA") concrete = stage.OverridePrim("/Concrete") items = None @@ -65,13 +65,13 @@ def test_BasicApi(self): def test_InheritedPrim(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory("x."+fmt) + stage = Usd.Stage.CreateInMemory(f"x.{fmt}") classA = stage.CreateClassPrim("/ClassA") stage.DefinePrim("/ClassA/Child") concrete = stage.DefinePrim("/Concrete") - assert not concrete.GetChildren() + assert not concrete.GetChildren() assert concrete.GetInherits().AddInherit(classA.GetPath()) self.assertEqual(concrete.GetChildren()[0].GetPath(), @@ -85,8 +85,8 @@ def test_InheritedPrim(self): def test_InheritPathMapping(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory("x."+fmt, sessionLayer=None) - + stage = Usd.Stage.CreateInMemory(f"x.{fmt}", sessionLayer=None) + # Create test scenegraph stage.DefinePrim("/Ref") stage.DefinePrim("/Ref/Class") @@ -114,13 +114,13 @@ def test_InheritPathMapping(self): # Add an inherit path to the instance prim pointing to the # class prim. instancePrim.GetInherits() \ - .AddInherit("/Model/Class", Usd.ListPositionFrontOfPrependList) + .AddInherit("/Model/Class", Usd.ListPositionFrontOfPrependList) expectedInheritPaths = Sdf.PathListOp() expectedInheritPaths.prependedItems = [Sdf.Path("/Ref/Class")] instancePrimSpec = \ - stage.GetRootLayer().GetPrimAtPath("/Ref/Instance") + stage.GetRootLayer().GetPrimAtPath("/Ref/Instance") self.assertEqual(instancePrimSpec.GetInfo("inheritPaths"), expectedInheritPaths) @@ -134,7 +134,7 @@ def test_InheritPathMapping(self): # Add a global inherit path. instancePrim.GetInherits() \ - .AddInherit("/Class", Usd.ListPositionFrontOfPrependList) + .AddInherit("/Class", Usd.ListPositionFrontOfPrependList) expectedInheritPaths = Sdf.PathListOp() expectedInheritPaths.prependedItems = [Sdf.Path("/Class")] @@ -155,7 +155,7 @@ def test_InheritPathMapping(self): # map across the reference edit target. with self.assertRaises(Tf.ErrorException): instancePrim.GetInherits() \ - .AddInherit("/Ref2/Class", Usd.ListPositionFrontOfPrependList) + .AddInherit("/Ref2/Class", Usd.ListPositionFrontOfPrependList) self.assertEqual(instancePrimSpec.GetInfo("inheritPaths"), expectedInheritPaths) @@ -167,7 +167,7 @@ def test_InheritPathMapping(self): self.assertEqual(instancePrimSpec.GetInfo("inheritPaths"), expectedInheritPaths) - + # Set inherit paths using the SetInherits API instancePrim.GetInherits().SetInherits( ["/Model/Class", "/Class"]) @@ -187,7 +187,7 @@ def test_InheritPathMapping(self): def test_InheritPathMappingVariants(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory("x."+fmt, sessionLayer=None) + stage = Usd.Stage.CreateInMemory(f"x.{fmt}", sessionLayer=None) # Create test scenegraph with variant refPrim = stage.DefinePrim("/Root") @@ -208,7 +208,7 @@ def test_InheritPathMappingVariants(self): # Check that authored inherit path does *not* include variant # selection. instancePrimSpec = \ - stage.GetRootLayer().GetPrimAtPath("/Root{v=x}Instance") + stage.GetRootLayer().GetPrimAtPath("/Root{v=x}Instance") expectedInheritPaths = Sdf.PathListOp() expectedInheritPaths.prependedItems = [Sdf.Path("/Root/Class")] self.assertEqual(instancePrimSpec.GetInfo('inheritPaths'), @@ -216,7 +216,7 @@ def test_InheritPathMappingVariants(self): def test_GetAllDirectInherits(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory('x.'+fmt, sessionLayer=None) + stage = Usd.Stage.CreateInMemory(f'x.{fmt}', sessionLayer=None) # Create a simple prim hierarchy, /Parent/Child, then add some arcs. child = stage.DefinePrim('/Parent/Child') @@ -249,11 +249,11 @@ def test_GetAllDirectInherits(self): def test_ListPosition(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory("x."+fmt, sessionLayer=None) + stage = Usd.Stage.CreateInMemory(f"x.{fmt}", sessionLayer=None) prim = stage.DefinePrim('/prim') for c in 'abcde': - stage.DefinePrim('/'+c) + stage.DefinePrim(f'/{c}') inh = prim.GetInherits() diff --git a/pxr/usd/lib/usd/testenv/testUsdInstanceProxy.py b/pxr/usd/lib/usd/testenv/testUsdInstanceProxy.py index 0c11a42f1ab..bb80a350d63 100644 --- a/pxr/usd/lib/usd/testenv/testUsdInstanceProxy.py +++ b/pxr/usd/lib/usd/testenv/testUsdInstanceProxy.py @@ -241,7 +241,7 @@ def test_LoadSet(self): master.GetPath().AppendPath('props/Prop_2')]) # Load and unload models through instance proxies. - self.assertFalse(all([p.IsLoaded() for p in loadableProps])) + self.assertFalse(all(p.IsLoaded() for p in loadableProps)) s.GetPrimAtPath('/World/sets/Set_1/props/Prop_1').Load() self.assertTrue( @@ -254,10 +254,10 @@ def test_LoadSet(self): s.GetPrimAtPath('/World/sets/Set_2/props/Prop_2').IsLoaded()) s.GetPrimAtPath('/World/sets/Set_2/props/Prop_2').Load() - self.assertTrue(all([p.IsLoaded() for p in loadableProps])) + self.assertTrue(all(p.IsLoaded() for p in loadableProps)) s.LoadAndUnload([], ['/World/sets/Set_1/props']) - self.assertFalse(all([p.IsLoaded() for p in loadableProps])) + self.assertFalse(all(p.IsLoaded() for p in loadableProps)) def test_PrimRange(self): s = Usd.Stage.Open('nested/root.usda') diff --git a/pxr/usd/lib/usd/testenv/testUsdInstancing.py b/pxr/usd/lib/usd/testenv/testUsdInstancing.py index 15f9e846146..882f32aa147 100644 --- a/pxr/usd/lib/usd/testenv/testUsdInstancing.py +++ b/pxr/usd/lib/usd/testenv/testUsdInstancing.py @@ -41,13 +41,13 @@ def ValidateExpectedInstances(stage, expectedInstances): # Validate that all prims expected to be instances of the same master # are associated with the same master prim. master = stage.GetPrimAtPath(masterPath) - assert master, "Expected master <%s> does not exist" % masterPath + assert master, f"Expected master <{masterPath}> does not exist" for p in instancePaths: prim = stage.GetPrimAtPath(p) - assert prim.IsInstance(), "Prim <%s> is not an instance" % p - assert prim.GetMaster() == master, \ - "Instance <%s> does not have expected master <%s>" % \ - (p, master.GetPath()) + assert prim.IsInstance(), f"Prim <{p}> is not an instance" + assert ( + prim.GetMaster() == master + ), f"Instance <{p}> does not have expected master <{master.GetPath()}>" # Validate that the master prim's source prim index is one of # the instance's prim indexes. @@ -68,10 +68,9 @@ def ValidateExpectedInstances(stage, expectedInstances): for root in [stage.GetPseudoRoot()] + stage.GetMasters(): for prim in Usd.PrimRange(root): if prim.IsInstance(): - assert str(prim.GetPath()) in \ - expectedInstances.get(str(prim.GetMaster().GetPath()), []), \ - "Found unexpected instance prim <%s> with master <%s>" % \ - (prim.GetPath(), prim.GetMaster().GetPath()) + assert str(prim.GetPath()) in expectedInstances.get( + str(prim.GetMaster().GetPath()), [] + ), f"Found unexpected instance prim <{prim.GetPath()}> with master <{prim.GetMaster().GetPath()}>" def ValidateExpectedChanges(noticeListener, expectedResyncs = [], expectedChangedInfo = []): @@ -79,15 +78,13 @@ def ValidateExpectedChanges(noticeListener, expectedResyncs = [], Validate the expected changes received by the noticeListener. expectedResyncs and expectedChangedInfo are lists of prim paths. """ - assert set(noticeListener.resyncedPrimPaths) == \ - set([Sdf.Path(p) for p in expectedResyncs]), \ - "Expected resyncs for %s, got %s" % \ - (set(expectedResyncs), noticeListener.resyncedPrimPaths) - - assert set(noticeListener.changedInfoPaths) == \ - set([Sdf.Path(p) for p in expectedChangedInfo]), \ - "Expected changed info for %s, got %s" % \ - (set(expectedChangedInfo), noticeListener.changedInfoPaths) + assert set(noticeListener.resyncedPrimPaths) == { + Sdf.Path(p) for p in expectedResyncs + }, f"Expected resyncs for {set(expectedResyncs)}, got {noticeListener.resyncedPrimPaths}" + + assert set(noticeListener.changedInfoPaths) == { + Sdf.Path(p) for p in expectedChangedInfo + }, f"Expected changed info for {set(expectedChangedInfo)}, got {noticeListener.changedInfoPaths}" def ValidateAndDumpUsdStage(stage): """ diff --git a/pxr/usd/lib/usd/testenv/testUsdMetadata.py b/pxr/usd/lib/usd/testenv/testUsdMetadata.py index 821047eba50..48936ddc48f 100644 --- a/pxr/usd/lib/usd/testenv/testUsdMetadata.py +++ b/pxr/usd/lib/usd/testenv/testUsdMetadata.py @@ -25,12 +25,12 @@ import sys, os, unittest from pxr import Sdf, Usd, Tf, Plug -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] class TestUsdMetadata(unittest.TestCase): def test_Hidden(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory('TestHidden.'+fmt) + stage = Usd.Stage.CreateInMemory(f'TestHidden.{fmt}') stageRoot = stage.GetPseudoRoot() foo = stage.OverridePrim("/Foo") @@ -316,7 +316,7 @@ def test_BasicCustomData(self): '''Test basic CustomData API, including by-key-path API''' for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestBasicCustomData.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestBasicCustomData.{fmt}') p = s.OverridePrim('/foo') assert not p.HasCustomData() @@ -399,7 +399,7 @@ def test_ComposedNestedDictionaries(self): def test_ComposedCustomData(self): '''Test customData composition (dictionary-wise)''' for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestComposedCustomData.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestComposedCustomData.{fmt}') # Create two prims, 'weaker' and 'stronger', 'stronger' references # 'weaker'. @@ -442,7 +442,7 @@ def test_BasicCustomDataViaMetadataAPI(self): '''Test basic metadata API, including by-key-path API''' for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestBasicCustomDataViaMetadataAPI.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestBasicCustomDataViaMetadataAPI.{fmt}') p = s.OverridePrim('/foo') assert not p.HasMetadata('customData') @@ -503,8 +503,7 @@ def test_BasicCustomDataViaMetadataAPI(self): def test_ComposedCustomDataViaMetadataAPI(self): '''Test customData composition (dictionary-wise)''' for fmt in allFormats: - s = Usd.Stage.CreateInMemory( - 'TestComposedCustomDataViaMetadataAPI.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestComposedCustomDataViaMetadataAPI.{fmt}') # Create two prims, 'weaker' and 'stronger', 'stronger' references # 'weaker'. @@ -559,7 +558,7 @@ def test_BasicRequiredFields(self): ('Ensure only expected required fields are returned by ' 'GetAllAuthoredMetadata, test for bug 98419') for fmt in allFormats: - a = Usd.Stage.CreateInMemory('TestBasicRequiredFields.'+fmt) + a = Usd.Stage.CreateInMemory(f'TestBasicRequiredFields.{fmt}') b = a.OverridePrim('/hello') attr = b.CreateAttribute('foo', Sdf.ValueTypeNames.Double) attr.Set(1.234) @@ -567,16 +566,15 @@ def test_BasicRequiredFields(self): outs = ['allowedTokens'] metadata = attr.GetAllAuthoredMetadata() for key in ins: - assert key in metadata, ("expected %s in %s" % (key, metadata)) + assert key in metadata, f"expected {key} in {metadata}" for key in outs: - assert key not in metadata, ("expected %s not in %s" % - (key, metadata)) + assert key not in metadata, f"expected {key} not in {metadata}" def test_BasicListOpMetadata(self): '''Tests basic metadata API with supported list op types''' def _TestBasic(fieldName, listOp, expectedListOp): for fmt in allFormats: - s = Usd.Stage.CreateNew("TestBasicListOpMetadata."+fmt) + s = Usd.Stage.CreateNew(f"TestBasicListOpMetadata.{fmt}") prim = s.OverridePrim('/Root') @@ -588,7 +586,7 @@ def _TestBasic(fieldName, listOp, expectedListOp): assert prim.HasMetadata(fieldName) assert prim.HasAuthoredMetadata(fieldName) self.assertEqual(prim.GetMetadata(fieldName), expectedListOp) - + prim.ClearMetadata(fieldName) assert not prim.HasMetadata(fieldName) assert not prim.HasAuthoredMetadata(fieldName) @@ -661,9 +659,9 @@ def _TestBasic(fieldName, listOp, expectedListOp): def test_ComposedListOpMetadata(self): '''Tests composition of list op-valued metadata fields''' def _TestComposition(fieldName, weakListOp, strongListOp, - expectedListOp): + expectedListOp): for fmt in allFormats: - s = Usd.Stage.CreateNew("TestComposedListOpMetadata."+fmt) + s = Usd.Stage.CreateNew(f"TestComposedListOpMetadata.{fmt}") ref = s.OverridePrim('/Ref') ref.SetMetadata(fieldName, weakListOp) @@ -729,7 +727,7 @@ def _TestComposition(fieldName, weakListOp, strongListOp, expectedListOp.explicitItems = [18446744073709551615, 3, 2, 1] _TestComposition('uint64ListOpTest', weakListOp, strongListOp, expectedListOp) - + # Sdf.StringListOp weakListOp = Sdf.StringListOp() weakListOp.explicitItems = ["baz"] @@ -860,46 +858,54 @@ def test_AssetPathMetadata(self): s = Usd.Stage.Open("assetPaths/root.usda") prim = s.GetPrimAtPath("/AssetPathTest") attr = prim.GetAttribute("assetPath") - + timeSamples = attr.GetMetadata("timeSamples") self.assertEqual(os.path.normpath(timeSamples[0].resolvedPath), os.path.abspath("assetPaths/asset.usda")) self.assertEqual(os.path.normpath(timeSamples[1].resolvedPath), os.path.abspath("assetPaths/asset.usda")) - + self.assertEqual( os.path.normpath(attr.GetMetadata("default").resolvedPath), os.path.abspath("assetPaths/asset.usda")) - + attr = s.GetPrimAtPath("/AssetPathTest").GetAttribute("assetPathArray") self.assertEqual( - list([os.path.normpath(p.resolvedPath) - for p in attr.GetMetadata("default")]), - [os.path.abspath("assetPaths/asset.usda")]) + [ + os.path.normpath(p.resolvedPath) + for p in attr.GetMetadata("default") + ], + [os.path.abspath("assetPaths/asset.usda")], + ) metadataDict = prim.GetMetadata("customData") self.assertEqual( os.path.normpath(metadataDict["assetPath"].resolvedPath), os.path.abspath("assetPaths/asset.usda")) self.assertEqual( - list([os.path.normpath(p.resolvedPath) - for p in metadataDict["assetPathArray"]]), - [os.path.abspath("assetPaths/asset.usda")]) - + [ + os.path.normpath(p.resolvedPath) + for p in metadataDict["assetPathArray"] + ], + [os.path.abspath("assetPaths/asset.usda")], + ) + metadataDict = metadataDict["subDict"] self.assertEqual( os.path.normpath(metadataDict["assetPath"].resolvedPath), os.path.abspath("assetPaths/asset.usda")) self.assertEqual( - list([os.path.normpath(p.resolvedPath) - for p in metadataDict["assetPathArray"]]), - [os.path.abspath("assetPaths/asset.usda")]) + [ + os.path.normpath(p.resolvedPath) + for p in metadataDict["assetPathArray"] + ], + [os.path.abspath("assetPaths/asset.usda")], + ) def test_TimeSamplesMetadata(self): '''Test timeSamples composition, with layer offsets''' for fmt in allFormats: - s = Usd.Stage.CreateInMemory( - 'TestTimeSamplesMetadata.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestTimeSamplesMetadata.{fmt}') # Create two prims, 'weaker' and 'stronger', 'stronger' references # 'weaker'. @@ -916,7 +922,7 @@ def test_TimeSamplesMetadata(self): # Set some time samples on the reference. weaker_attr = \ - weaker.CreateAttribute("attr", Sdf.ValueTypeNames.String) + weaker.CreateAttribute("attr", Sdf.ValueTypeNames.String) # We write directly to the weaker_attr, as opposed to # writing to stronger_attr with an edit target (which # would give the same result). diff --git a/pxr/usd/lib/usd/testenv/testUsdModel.py b/pxr/usd/lib/usd/testenv/testUsdModel.py index dfb529f058b..59d82f5fb9a 100644 --- a/pxr/usd/lib/usd/testenv/testUsdModel.py +++ b/pxr/usd/lib/usd/testenv/testUsdModel.py @@ -25,12 +25,12 @@ import unittest from pxr import Usd, Sdf, Kind -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] class TestUsdModel(unittest.TestCase): def test_ModelKind(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestModelKind.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestModelKind.{fmt}') p = s.DefinePrim('/World', 'Xform') model = Usd.ModelAPI(p) self.assertEqual(model.GetKind(), '') @@ -54,7 +54,7 @@ def test_ModelKind(self): def test_ModelHierarchy(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestModelHierarchy.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestModelHierarchy.{fmt}') x = s.DefinePrim('/X', 'Scope') y = s.DefinePrim('/X/Y', 'Scope') z = s.DefinePrim('/X/Y/Z', 'Scope') @@ -97,7 +97,7 @@ def test_ModelHierarchy(self): def test_AssetInfo(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestAssetInfo.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestAssetInfo.{fmt}') p = s.DefinePrim('/World', 'Xform') model = Usd.ModelAPI(p) @@ -143,7 +143,7 @@ def test_AssetInfo(self): # currently possible. def test_ModelAPI(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestModelAPI.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestModelAPI.{fmt}') p = s.DefinePrim('/World', 'Xform') model = Usd.ModelAPI(p) self.assertEqual(model.GetKind(), '') diff --git a/pxr/usd/lib/usd/testenv/testUsdNotices.py b/pxr/usd/lib/usd/testenv/testUsdNotices.py index c8bbf915d8d..9baa3a38c83 100644 --- a/pxr/usd/lib/usd/testenv/testUsdNotices.py +++ b/pxr/usd/lib/usd/testenv/testUsdNotices.py @@ -25,7 +25,7 @@ import sys, unittest from pxr import Sdf,Usd,Tf -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] class NoticeTester(unittest.TestCase): def setUp(self): @@ -62,7 +62,7 @@ def Basics(self): for fmt in allFormats: self._ResetCounters() - s = Usd.Stage.CreateInMemory('Basics.'+fmt) + s = Usd.Stage.CreateInMemory(f'Basics.{fmt}') s.DefinePrim("/Foo") self.assertEqual(self._changeCount, 2) self.assertEqual(self._contentsCount, 1) @@ -81,10 +81,6 @@ def Basics(self): self.assertEqual(self._changeCount, 4) self.assertEqual(self._contentsCount, 2) # Why 2? I expected 1. self.assertEqual(self._objectsCount, 2) # We get an additional - # object resync notice when - # we first drop an over, in - # addition to the info-only - # change notice. self.assertEqual(self._editTargetsCount, 0) self._ResetCounters() @@ -102,7 +98,7 @@ def Basics(self): self.assertTrue(self._objectsCount == 0) payloadBasedFile = 'payload_base.usda' payloadBasedStage = Usd.Stage.Open(payloadBasedFile) - + # the payload will be already loaded since we didn't supply # the additional parameter to the stage constructor payloadBasedStage.Unload('/Foo') @@ -134,7 +130,7 @@ def OnUpdate(notice, stage): for fmt in allFormats: self._ResetCounters() - s = Usd.Stage.CreateInMemory('ObjectsChangedNotice.'+fmt) + s = Usd.Stage.CreateInMemory(f'ObjectsChangedNotice.{fmt}') objectsChanged = Tf.Notice.Register(Usd.Notice.ObjectsChanged, OnResync, s) @@ -148,7 +144,7 @@ def OnUpdate(notice, stage): def ObjectsChangedNoticeForAttributes(self): for fmt in allFormats: self._ResetCounters() - s = Usd.Stage.CreateInMemory('ObjectsChangedNoticeForProps.'+fmt) + s = Usd.Stage.CreateInMemory(f'ObjectsChangedNoticeForProps.{fmt}') prim = s.DefinePrim("/Foo"); def OnAttributeCreation(notice, stage): @@ -167,7 +163,7 @@ def OnAttributeValueChange(notice, stage): self.assertEqual(notice.GetStage(), stage) self.assertEqual(notice.GetResyncedPaths(), []) self.assertTrue(notice.GetChangedInfoOnlyPaths() == \ - [Sdf.Path("/Foo.attr")]) + [Sdf.Path("/Foo.attr")]) self.assertTrue(notice.AffectedObject( stage.GetPrimAtPath("/Foo").GetAttribute("attr"))) self.assertTrue(not notice.ResyncedObject( @@ -184,7 +180,7 @@ def OnAttributeValueChange(notice, stage): def ObjectsChangedNoticeForRelationships(self): for fmt in allFormats: self._ResetCounters() - s = Usd.Stage.CreateInMemory('ObjectsChangedNoticeForRels.'+fmt) + s = Usd.Stage.CreateInMemory(f'ObjectsChangedNoticeForRels.{fmt}') prim = s.DefinePrim("/Foo"); def OnRelationshipCreation(notice, stage): diff --git a/pxr/usd/lib/usd/testenv/testUsdPayloads.py b/pxr/usd/lib/usd/testenv/testUsdPayloads.py index 1007c1c8142..1ee91c60cc0 100644 --- a/pxr/usd/lib/usd/testenv/testUsdPayloads.py +++ b/pxr/usd/lib/usd/testenv/testUsdPayloads.py @@ -25,7 +25,7 @@ import os, sys, unittest from pxr import Gf, Tf, Sdf, Pcp, Usd -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] class PayloadedScene(object): # @@ -49,30 +49,30 @@ def __init__(self, fmt): # /Corge/Waldo/Fred # Create payload1.fmt - self.payload1 = Usd.Stage.CreateInMemory("payload1."+fmt) + self.payload1 = Usd.Stage.CreateInMemory(f"payload1.{fmt}") p = self.payload1.DefinePrim("/Sad/Panda", "Scope") # Create payload3.fmt - self.payload3 = Usd.Stage.CreateInMemory("payload3."+fmt) + self.payload3 = Usd.Stage.CreateInMemory(f"payload3.{fmt}") p = self.payload3.DefinePrim("/Garply/Qux", "Scope") # Create payload2.fmt # Intentionally using the metadata API. - self.payload2 = Usd.Stage.CreateInMemory("payload2."+fmt) + self.payload2 = Usd.Stage.CreateInMemory(f"payload2.{fmt}") p = self.payload2.DefinePrim("/Baz/Garply", "Scope") p.SetMetadata("payload", Sdf.Payload(self.payload3.GetRootLayer().identifier, "/Garply")) # Create payload4.fmt - self.payload4 = Usd.Stage.CreateInMemory("payload4."+fmt) + self.payload4 = Usd.Stage.CreateInMemory(f"payload4.{fmt}") p = self.payload4.DefinePrim("/Corge/Waldo/Fred", "Scope") # # Create the scene that references payload1 and payload2 # # Intentionally using the prim-payload API. - self.stage = Usd.Stage.CreateInMemory("scene."+fmt) + self.stage = Usd.Stage.CreateInMemory(f"scene.{fmt}") p = self.stage.DefinePrim("/Sad", "Scope") p.SetPayload(Sdf.Payload(self.payload1.GetRootLayer().identifier, "/Sad")) @@ -163,10 +163,17 @@ def test_InstancesWithPayloads(self): for fmt in allFormats: p = InstancedAndPayloadedScene(fmt) - self.assertEqual(set(p.stage.FindLoadable()), - set([Sdf.Path("/Sad"), Sdf.Path("/Sad_1"), - Sdf.Path("/Foo/Baz"), Sdf.Path("/Foo/Baz_1"), - Sdf.Path("/Bar"), Sdf.Path("/Bar_1")])) + self.assertEqual( + set(p.stage.FindLoadable()), + { + Sdf.Path("/Sad"), + Sdf.Path("/Sad_1"), + Sdf.Path("/Foo/Baz"), + Sdf.Path("/Foo/Baz_1"), + Sdf.Path("/Bar"), + Sdf.Path("/Bar_1"), + }, + ) sad = p.stage.GetPrimAtPath("/Sad") sad_1 = p.stage.GetPrimAtPath("/Sad_1") diff --git a/pxr/usd/lib/usd/testenv/testUsdPrimRange.py b/pxr/usd/lib/usd/testenv/testUsdPrimRange.py index f9d74f587f6..73fb0432c6f 100644 --- a/pxr/usd/lib/usd/testenv/testUsdPrimRange.py +++ b/pxr/usd/lib/usd/testenv/testUsdPrimRange.py @@ -25,12 +25,12 @@ import unittest from pxr import Sdf, Usd -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] class TestUsdPrimRange(unittest.TestCase): def test_PrimIsDefined(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestPrimIsDefined.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestPrimIsDefined.{fmt}') pseudoRoot = s.GetPrimAtPath("/") foo = s.DefinePrim("/Foo", "Mesh") bar = s.OverridePrim("/Bar") @@ -56,7 +56,7 @@ def test_PrimIsDefined(self): def test_PrimHasDefiningSpecifier(self): for fmt in allFormats: - stageFile = 'testHasDefiningSpecifier.' + fmt + stageFile = f'testHasDefiningSpecifier.{fmt}' stage = Usd.Stage.Open(stageFile) # In the case of nested overs and defs, the onus is @@ -64,20 +64,22 @@ def test_PrimHasDefiningSpecifier(self): # restarting iteration upon hitting an over, or by iterating # through all prims. root = stage.GetPrimAtPath('/a1') - actual = [] expected = [stage.GetPrimAtPath(x) for x in ['/a1', '/a1/a2']] - for prim in Usd.PrimRange.AllPrims(root): - if prim.HasDefiningSpecifier(): - actual.append(prim) + actual = [ + prim + for prim in Usd.PrimRange.AllPrims(root) + if prim.HasDefiningSpecifier() + ] self.assertEqual(actual, expected) root = stage.GetPrimAtPath('/b1') - actual = [] expected = [stage.GetPrimAtPath(x) for x in ['/b1/b2', '/b1/b2/b3/b4/b5/b6']] - for prim in Usd.PrimRange(root, Usd.PrimIsActive): - if prim.HasDefiningSpecifier(): - actual.append(prim) + actual = [ + prim + for prim in Usd.PrimRange(root, Usd.PrimIsActive) + if prim.HasDefiningSpecifier() + ] self.assertEqual(actual, expected) # Note that the over is not included in our traversal. @@ -89,7 +91,7 @@ def test_PrimHasDefiningSpecifier(self): def test_PrimIsActive(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestPrimIsActive.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestPrimIsActive.{fmt}') foo = s.DefinePrim("/Foo", "Mesh") bar = s.DefinePrim("/Foo/Bar", "Mesh") baz = s.DefinePrim("/Foo/Bar/Baz", "Mesh") @@ -112,7 +114,7 @@ def test_PrimIsActive(self): def test_PrimIsModelOrGroup(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestPrimIsModelOrGroup.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestPrimIsModelOrGroup.{fmt}') group = s.DefinePrim("/Group", "Xform") Usd.ModelAPI(group).SetKind('group') model = s.DefinePrim("/Group/Model", "Model") @@ -141,7 +143,7 @@ def test_PrimIsModelOrGroup(self): def test_PrimIsAbstract(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestPrimIsAbstract.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestPrimIsAbstract.{fmt}') group = s.DefinePrim("/Group", "Xform") c = s.CreateClassPrim("/class_Model") @@ -159,10 +161,10 @@ def test_PrimIsAbstract(self): def test_PrimIsLoaded(self): for fmt in allFormats: - payloadStage = Usd.Stage.CreateInMemory("payload."+fmt) + payloadStage = Usd.Stage.CreateInMemory(f"payload.{fmt}") p = payloadStage.DefinePrim("/Payload", "Scope") - stage = Usd.Stage.CreateInMemory("scene."+fmt) + stage = Usd.Stage.CreateInMemory(f"scene.{fmt}") foo = stage.DefinePrim("/Foo") foo.SetPayload(payloadStage.GetRootLayer(), "/Payload") @@ -186,10 +188,10 @@ def test_PrimIsLoaded(self): def test_PrimIsInstanceOrMasterOrRoot(self): for fmt in allFormats: - refStage = Usd.Stage.CreateInMemory("reference."+fmt) + refStage = Usd.Stage.CreateInMemory(f"reference.{fmt}") refStage.DefinePrim("/Ref/Child") - stage = Usd.Stage.CreateInMemory("scene."+fmt) + stage = Usd.Stage.CreateInMemory(f"scene.{fmt}") root = stage.DefinePrim("/Root") i = stage.DefinePrim("/Root/Instance") @@ -216,7 +218,7 @@ def test_PrimIsInstanceOrMasterOrRoot(self): def test_RoundTrip(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory('TestRoundTrip.'+fmt) + stage = Usd.Stage.CreateInMemory(f'TestRoundTrip.{fmt}') prims = map(stage.DefinePrim, ['/foo', '/bar', '/baz']) treeRange = Usd.PrimRange(stage.GetPseudoRoot()) @@ -231,7 +233,7 @@ def test_RoundTrip(self): def test_StageTraverse(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestStageTraverse.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestStageTraverse.{fmt}') pseudoRoot = s.GetPrimAtPath("/") foo = s.DefinePrim("/Foo", "Mesh") bar = s.OverridePrim("/Bar") @@ -261,10 +263,10 @@ def test_StageTraverse(self): def test_WithInstancing(self): for fmt in allFormats: - refStage = Usd.Stage.CreateInMemory("reference."+fmt) + refStage = Usd.Stage.CreateInMemory(f"reference.{fmt}") refStage.DefinePrim("/Ref/Child") - stage = Usd.Stage.CreateInMemory("scene."+fmt) + stage = Usd.Stage.CreateInMemory(f"scene.{fmt}") root = stage.DefinePrim("/Root") i = stage.DefinePrim("/Root/Instance") diff --git a/pxr/usd/lib/usd/testenv/testUsdPrims.py b/pxr/usd/lib/usd/testenv/testUsdPrims.py index 572e5f9596c..a6901fa33e5 100644 --- a/pxr/usd/lib/usd/testenv/testUsdPrims.py +++ b/pxr/usd/lib/usd/testenv/testUsdPrims.py @@ -25,12 +25,12 @@ import sys, unittest from pxr import Sdf,Usd,Tf -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] class TestUsdPrim(unittest.TestCase): def test_Basic(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('Basics.'+fmt) + s = Usd.Stage.CreateInMemory(f'Basics.{fmt}') p = s.GetPrimAtPath('/') q = s.GetPrimAtPath('/') assert p is not q @@ -63,8 +63,8 @@ def test_Basic(self): def test_OverrideMetadata(self): for fmt in allFormats: - weak = Sdf.Layer.CreateAnonymous('OverrideMetadataTest.'+fmt) - strong = Sdf.Layer.CreateAnonymous('OverrideMetadataTest.'+fmt) + weak = Sdf.Layer.CreateAnonymous(f'OverrideMetadataTest.{fmt}') + strong = Sdf.Layer.CreateAnonymous(f'OverrideMetadataTest.{fmt}') stage = Usd.Stage.Open(weak.identifier) assert stage.DefinePrim("/Mesh/Child", "Mesh") @@ -75,7 +75,7 @@ def test_OverrideMetadata(self): p = stage.GetPrimAtPath("/Mesh/Child") assert p assert p.SetMetadata( - "hidden", False), "Failed to set metadata in stronger layer" + "hidden", False), "Failed to set metadata in stronger layer" assert p.GetName() == p.GetPath().name def test_GetPrimStack(self): @@ -115,10 +115,10 @@ def test_GetPrimStack(self): def test_GetCachedPrimBits(self): layerFile = 'test.usda' layer = Sdf.Layer.FindOrOpen(layerFile) - assert layer, 'failed to find "%s"' % layerFile + assert layer, f'failed to find "{layerFile}"' stage = Usd.Stage.Open(layer, load=Usd.Stage.LoadNone) - assert stage, 'failed to create stage for %s' % layerFile + assert stage, f'failed to create stage for {layerFile}' # Check various bits. root = stage.GetPrimAtPath('/') @@ -384,7 +384,7 @@ def test_GetCachedPrimBits(self): def test_ChangeTypeName(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('ChangeTypeName.'+fmt) + s = Usd.Stage.CreateInMemory(f'ChangeTypeName.{fmt}') foo = s.OverridePrim("/Foo") # Initialize @@ -412,13 +412,13 @@ def test_ChangeTypeName(self): def test_HasAuthoredReferences(self): for fmt in allFormats: - s1 = Usd.Stage.CreateInMemory('HasAuthoredReferences.'+fmt) + s1 = Usd.Stage.CreateInMemory(f'HasAuthoredReferences.{fmt}') s1.DefinePrim("/Foo", "Mesh") s1.DefinePrim("/Bar", "Mesh") baz = s1.DefinePrim("/Foo/Baz", "Mesh") assert baz.GetReferences().AddReference(s1.GetRootLayer().identifier, "/Bar") - s2 = Usd.Stage.CreateInMemory('HasAuthoredReferences.'+fmt) + s2 = Usd.Stage.CreateInMemory(f'HasAuthoredReferences.{fmt}') foo = s2.OverridePrim("/Foo") baz = s2.GetPrimAtPath("/Foo/Baz") @@ -485,33 +485,35 @@ def test_GoodAndBadReferences(self): def test_PropertyOrder(self): layerFile = 'test.usda' layer = Sdf.Layer.FindOrOpen(layerFile) - assert layer, 'failed to find "%s"' % layerFile + assert layer, f'failed to find "{layerFile}"' stage = Usd.Stage.Open(layer, load=Usd.Stage.LoadNone) - assert stage, 'failed to create stage for %s' % layerFile + assert stage, f'failed to create stage for {layerFile}' po = stage.GetPrimAtPath('/PropertyOrder') assert po attrs = po.GetAttributes() # expected order: expected = ['A0', 'a1', 'a2', 'A3', 'a4', 'a5', 'a10', 'A20'] - assert [a.GetName() for a in attrs] == expected, \ - '%s != %s' % ([a.GetName() for a in attrs], expected) + assert [ + a.GetName() for a in attrs + ] == expected, f'{[a.GetName() for a in attrs]} != {expected}' rels = po.GetRelationships() # expected order: expected = ['R0', 'r1', 'r2', 'R3', 'r4', 'r5', 'r10', 'R20'] - assert [r.GetName() for r in rels] == expected, \ - '%s != %s' % ([r.GetName() for r in rels], expected) + assert [ + r.GetName() for r in rels + ] == expected, f'{[r.GetName() for r in rels]} != {expected}' def test_PropertyReorder(self): def l(chars): - return list(x for x in chars) + return list(chars) for fmt in allFormats: sl = Sdf.Layer.CreateAnonymous(fmt) - s = Usd.Stage.CreateInMemory('PropertyReorder.'+fmt, sl) + s = Usd.Stage.CreateInMemory(f'PropertyReorder.{fmt}', sl) f = s.OverridePrim('/foo') s.SetEditTarget(s.GetRootLayer()) @@ -558,7 +560,7 @@ def l(chars): def test_DefaultPrim(self): for fmt in allFormats: # No default prim to start. - s = Usd.Stage.CreateInMemory('DefaultPrim.'+fmt) + s = Usd.Stage.CreateInMemory(f'DefaultPrim.{fmt}') assert not s.GetDefaultPrim() # Set defaultPrim metadata on root layer, but no prim in scene @@ -639,31 +641,35 @@ def test_PrimOrder(self): orderAfter = ['Baz', 'Foo', 'Bar'] for fmt in allFormats: - s = Usd.Stage.CreateInMemory('PrimOrder.'+fmt) - children = [s.DefinePrim('/' + p) for p in orderBefore] + s = Usd.Stage.CreateInMemory(f'PrimOrder.{fmt}') + children = [s.DefinePrim(f'/{p}') for p in orderBefore] self.assertEqual(s.GetPseudoRoot().GetChildren(), children) # Author reorder, assert they are reordered. s.GetPseudoRoot().SetMetadata('primOrder', orderAfter) - self.assertEqual(s.GetPseudoRoot().GetChildren(), - [s.GetPrimAtPath('/' + p) for p in orderAfter]) + self.assertEqual( + s.GetPseudoRoot().GetChildren(), + [s.GetPrimAtPath(f'/{p}') for p in orderAfter], + ) # Try the same thing with non-root prims. - s = Usd.Stage.CreateInMemory('PrimOrder.'+fmt) - children = [s.DefinePrim('/Root/' + p) for p in orderBefore] + s = Usd.Stage.CreateInMemory(f'PrimOrder.{fmt}') + children = [s.DefinePrim(f'/Root/{p}') for p in orderBefore] self.assertEqual(s.GetPrimAtPath('/Root').GetChildren(), children) # Author reorder, assert they are reordered. s.GetPrimAtPath('/Root').SetMetadata('primOrder', orderAfter) - self.assertEqual(s.GetPrimAtPath('/Root').GetChildren(), - [s.GetPrimAtPath('/Root/' + p) for p in orderAfter]) + self.assertEqual( + s.GetPrimAtPath('/Root').GetChildren(), + [s.GetPrimAtPath(f'/Root/{p}') for p in orderAfter], + ) def test_Instanceable(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('Instanceable.'+fmt) + s = Usd.Stage.CreateInMemory(f'Instanceable.{fmt}') p = s.DefinePrim('/Instanceable', 'Mesh') assert not p.IsInstanceable() - assert p.GetMetadata('instanceable') == None + assert p.GetMetadata('instanceable') is None assert not p.HasAuthoredInstanceable() p.SetInstanceable(True) @@ -678,7 +684,7 @@ def test_Instanceable(self): p.ClearInstanceable() assert not p.IsInstanceable() - assert p.GetMetadata('instanceable') == None + assert p.GetMetadata('instanceable') is None assert not p.HasAuthoredInstanceable() def test_GetComposedPrimChildrenAsMetadataTest(self): @@ -692,7 +698,7 @@ def test_GetComposedPrimChildrenAsMetadataTest(self): def test_GetPrimIndex(self): def _CreateTestStage(fmt): - s = Usd.Stage.CreateInMemory('GetPrimIndex.'+fmt) + s = Usd.Stage.CreateInMemory(f'GetPrimIndex.{fmt}') c = s.DefinePrim('/Class') @@ -736,7 +742,7 @@ def _ValidateNoPrimIndexes(prim): def test_PseudoRoot(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('PseudoRoot.%s' % fmt) + s = Usd.Stage.CreateInMemory(f'PseudoRoot.{fmt}') w = s.DefinePrim('/World') p = s.GetPrimAtPath('/') self.assertTrue(p.IsPseudoRoot()) @@ -747,7 +753,7 @@ def test_PseudoRoot(self): def test_Deactivation(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('Deactivation.%s' % fmt) + s = Usd.Stage.CreateInMemory(f'Deactivation.{fmt}') child = s.DefinePrim('/Root/Group/Child') group = s.GetPrimAtPath('/Root/Group') @@ -778,8 +784,8 @@ def test_AppliedSchemas(self): self.assertTrue(Usd.CollectionAPI.IsMultipleApply()) for fmt in allFormats: - sessionLayer = Sdf.Layer.CreateNew("SessionLayer.%s" % fmt) - s = Usd.Stage.CreateInMemory('AppliedSchemas.%s' % fmt, sessionLayer) + sessionLayer = Sdf.Layer.CreateNew(f"SessionLayer.{fmt}") + s = Usd.Stage.CreateInMemory(f'AppliedSchemas.{fmt}', sessionLayer) s.SetEditTarget(Usd.EditTarget(s.GetRootLayer())) diff --git a/pxr/usd/lib/usd/testenv/testUsdReferences.py b/pxr/usd/lib/usd/testenv/testUsdReferences.py index 975c3eddab0..0b65dae2492 100644 --- a/pxr/usd/lib/usd/testenv/testUsdReferences.py +++ b/pxr/usd/lib/usd/testenv/testUsdReferences.py @@ -25,16 +25,16 @@ import sys, unittest from pxr import Sdf,Pcp,Usd,Tf -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] class TestUsdReferences(unittest.TestCase): def test_API(self): for fmt in allFormats: - s1 = Usd.Stage.CreateInMemory('API-s1.'+fmt) - s2 = Usd.Stage.CreateInMemory('API-s2.'+fmt) + s1 = Usd.Stage.CreateInMemory(f'API-s1.{fmt}') + s2 = Usd.Stage.CreateInMemory(f'API-s2.{fmt}') srcPrim = s1.OverridePrim('/src') trgPrimInternal = s1.OverridePrim('/trg_internal') - srcPrimSpec = s1.GetRootLayer().GetPrimAtPath('/src') + srcPrimSpec = s1.GetRootLayer().GetPrimAtPath('/src') trgPrim = s2.OverridePrim('/trg') s2.GetRootLayer().defaultPrim = 'trg' @@ -84,7 +84,7 @@ def test_API(self): def test_DefaultPrimBasics(self): # create a layer, set DefaultPrim, then reference it. for fmt in allFormats: - targLyr = Sdf.Layer.CreateAnonymous('DefaultPrimBasics.'+fmt) + targLyr = Sdf.Layer.CreateAnonymous(f'DefaultPrimBasics.{fmt}') def makePrim(name, attrDefault): primSpec = Sdf.CreatePrimInLayer(targLyr, name) @@ -99,7 +99,7 @@ def makePrim(name, attrDefault): targLyr.defaultPrim = 'target1' # create a new layer and reference the first. - srcLyr = Sdf.Layer.CreateAnonymous('DefaultPrimBasics-new.'+fmt) + srcLyr = Sdf.Layer.CreateAnonymous(f'DefaultPrimBasics-new.{fmt}') srcPrimSpec = Sdf.CreatePrimInLayer(srcLyr, '/source') # create a stage with srcLyr. @@ -117,7 +117,7 @@ def makePrim(name, attrDefault): def test_DefaultPrimChangeProcessing(self): for fmt in allFormats: # create a layer, set DefaultPrim, then reference it. - targLyr = Sdf.Layer.CreateAnonymous('DefaultPrimChangeProcessing.'+fmt) + targLyr = Sdf.Layer.CreateAnonymous(f'DefaultPrimChangeProcessing.{fmt}') def makePrim(name, attrDefault): primSpec = Sdf.CreatePrimInLayer(targLyr, name) @@ -132,8 +132,7 @@ def makePrim(name, attrDefault): targLyr.defaultPrim = 'target1' # create a new layer and reference the first. - srcLyr = Sdf.Layer.CreateAnonymous( - 'DefaultPrimChangeProcessing-new.'+fmt) + srcLyr = Sdf.Layer.CreateAnonymous(f'DefaultPrimChangeProcessing-new.{fmt}') srcPrimSpec = Sdf.CreatePrimInLayer(srcLyr, '/source') srcPrimSpec.referenceList.Add(Sdf.Reference(targLyr.identifier)) @@ -158,7 +157,7 @@ def makePrim(name, attrDefault): def test_InternalReferences(self): for fmt in allFormats: - targLyr = Sdf.Layer.CreateAnonymous('InternalReferences.'+fmt) + targLyr = Sdf.Layer.CreateAnonymous(f'InternalReferences.{fmt}') def makePrim(name, attrDefault): primSpec = Sdf.CreatePrimInLayer(targLyr, name) @@ -188,8 +187,8 @@ def makePrim(name, attrDefault): def test_SubrootReferences(self): for fmt in allFormats: - refLayer = Sdf.Layer.CreateAnonymous('SubrootReferences.'+fmt) - + refLayer = Sdf.Layer.CreateAnonymous(f'SubrootReferences.{fmt}') + def makePrim(name, attrDefault): primSpec = Sdf.CreatePrimInLayer(refLayer, name) primSpec.specifier = Sdf.SpecifierDef @@ -220,7 +219,7 @@ def makePrim(name, attrDefault): def test_PrependVsAppend(self): for fmt in allFormats: - layer = Sdf.Layer.CreateAnonymous('PrependVsAppend.'+fmt) + layer = Sdf.Layer.CreateAnonymous(f'PrependVsAppend.{fmt}') def makePrim(name, attrDefault): primSpec = Sdf.CreatePrimInLayer(layer, name) @@ -259,14 +258,14 @@ def makePrim(name, attrDefault): def test_InternalReferenceMapping(self): for fmt in allFormats: # Create test scenegraph - refLayer = Sdf.Layer.CreateAnonymous('InternalRefMapping_ref.'+fmt) + refLayer = Sdf.Layer.CreateAnonymous(f'InternalRefMapping_ref.{fmt}') refSpec = Sdf.PrimSpec(refLayer, 'Ref', Sdf.SpecifierDef) subRefSpec = Sdf.PrimSpec(refSpec, 'SubrootRef', Sdf.SpecifierDef) childRefSpec = Sdf.PrimSpec(refSpec, 'Child', Sdf.SpecifierDef) refSpec2 = Sdf.PrimSpec(refLayer, 'Ref2', Sdf.SpecifierDef) childRefSpec2 = Sdf.PrimSpec(refSpec2, 'Child', Sdf.SpecifierDef) - stage = Usd.Stage.CreateInMemory('InternalRefMapping.'+fmt) + stage = Usd.Stage.CreateInMemory(f'InternalRefMapping.{fmt}') prim = stage.DefinePrim('/Root') prim.GetReferences().AddReference(refLayer.identifier, refSpec.path) prim = stage.GetPrimAtPath('/Root') @@ -326,7 +325,7 @@ def test_InternalReferenceMapping(self): def test_InternalReferenceMappingVariants(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory("x."+fmt, sessionLayer=None) + stage = Usd.Stage.CreateInMemory(f"x.{fmt}", sessionLayer=None) # Create test scenegraph with variant refPrim = stage.DefinePrim("/Root") @@ -336,7 +335,7 @@ def test_InternalReferenceMappingVariants(self): with vset.GetVariantEditContext(): stage.DefinePrim("/Root/SubrootRef") stage.DefinePrim("/Root/Child") - + # Set edit target inside the variant and add a internal sub-root # reference to another prim in the same variant. with vset.GetVariantEditContext(): @@ -347,7 +346,7 @@ def test_InternalReferenceMappingVariants(self): # Check that authored reference does *not* include variant # selection. childPrimSpec = \ - stage.GetRootLayer().GetPrimAtPath("/Root{v=x}Child") + stage.GetRootLayer().GetPrimAtPath("/Root{v=x}Child") expectedRefs = Sdf.ReferenceListOp() expectedRefs.prependedItems = [ Sdf.Reference(primPath="/Root/SubrootRef") diff --git a/pxr/usd/lib/usd/testenv/testUsdRelationships.py b/pxr/usd/lib/usd/testenv/testUsdRelationships.py index 2bcfb1375b7..6dc1adebcde 100644 --- a/pxr/usd/lib/usd/testenv/testUsdRelationships.py +++ b/pxr/usd/lib/usd/testenv/testUsdRelationships.py @@ -25,10 +25,10 @@ import sys, unittest from pxr import Sdf, Tf, Usd -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] def _CreateStage(fmt): - s = Usd.Stage.CreateInMemory('_CreateStage.'+fmt) + s = Usd.Stage.CreateInMemory(f'_CreateStage.{fmt}') s.GetRootLayer().ImportFromString('''#usda 1.0 def Scope "Foo" { @@ -137,46 +137,92 @@ def test_Targets(self): recursive = stage.GetPrimAtPath("/Recursive") self.assertEqual( set(recursive.FindAllRelationshipTargetPaths()), - set([Sdf.Path('/Recursive/A'), Sdf.Path('/Recursive/B'), - Sdf.Path('/Recursive/C'), Sdf.Path('/Recursive/D'), - Sdf.Path('/Recursive/D/A'), Sdf.Path('/Recursive/D/B'), - Sdf.Path('/Recursive/D/C'), Sdf.Path('/Recursive/D/D')])) + { + Sdf.Path('/Recursive/A'), + Sdf.Path('/Recursive/B'), + Sdf.Path('/Recursive/C'), + Sdf.Path('/Recursive/D'), + Sdf.Path('/Recursive/D/A'), + Sdf.Path('/Recursive/D/B'), + Sdf.Path('/Recursive/D/C'), + Sdf.Path('/Recursive/D/D'), + }, + ) self.assertEqual( - set(recursive.FindAllRelationshipTargetPaths( - predicate = lambda rel: rel.GetPrim().GetName() in ('B', 'D'))), - set([Sdf.Path('/Recursive/A'), Sdf.Path('/Recursive/C'), - Sdf.Path('/Recursive/D/A'), Sdf.Path('/Recursive/D/C')])) + set( + recursive.FindAllRelationshipTargetPaths( + predicate=lambda rel: rel.GetPrim().GetName() in ('B', 'D') + ) + ), + { + Sdf.Path('/Recursive/A'), + Sdf.Path('/Recursive/C'), + Sdf.Path('/Recursive/D/A'), + Sdf.Path('/Recursive/D/C'), + }, + ) self.assertEqual( - set(recursive.FindAllRelationshipTargetPaths( - predicate = lambda rel: rel.GetPrim().GetName() in ('A', 'C'))), - set([Sdf.Path('/Recursive/B'), Sdf.Path('/Recursive/D'), - Sdf.Path('/Recursive/D/B'), Sdf.Path('/Recursive/D/D')])) - + set( + recursive.FindAllRelationshipTargetPaths( + predicate=lambda rel: rel.GetPrim().GetName() in ('A', 'C') + ) + ), + { + Sdf.Path('/Recursive/B'), + Sdf.Path('/Recursive/D'), + Sdf.Path('/Recursive/D/B'), + Sdf.Path('/Recursive/D/D'), + }, + ) + recursiveA = stage.GetPrimAtPath("/Recursive/A") - self.assertEqual(set(recursiveA.FindAllRelationshipTargetPaths()), - set([Sdf.Path('/Recursive/B')])) - - self.assertEqual(set( - recursiveA.FindAllRelationshipTargetPaths(recurseOnTargets=True)), - set([Sdf.Path('/Recursive/A'), Sdf.Path('/Recursive/B'), - Sdf.Path('/Recursive/C'), Sdf.Path('/Recursive/D'), - Sdf.Path('/Recursive/D/A'), Sdf.Path('/Recursive/D/B'), - Sdf.Path('/Recursive/D/C'), Sdf.Path('/Recursive/D/D')])) - - self.assertEqual(set( - recursiveA.FindAllRelationshipTargetPaths( - recurseOnTargets=True, - predicate=lambda rel: rel.GetPrim().GetParent().GetName() == - 'Recursive' or rel.GetPrim().GetName() in ('A', 'C'))), - set([Sdf.Path('/Recursive/A'), Sdf.Path('/Recursive/B'), - Sdf.Path('/Recursive/C'), Sdf.Path('/Recursive/D'), - Sdf.Path('/Recursive/D/B'), Sdf.Path('/Recursive/D/D')])) + self.assertEqual( + set(recursiveA.FindAllRelationshipTargetPaths()), + {Sdf.Path('/Recursive/B')}, + ) + + self.assertEqual( + set( + recursiveA.FindAllRelationshipTargetPaths( + recurseOnTargets=True + ) + ), + { + Sdf.Path('/Recursive/A'), + Sdf.Path('/Recursive/B'), + Sdf.Path('/Recursive/C'), + Sdf.Path('/Recursive/D'), + Sdf.Path('/Recursive/D/A'), + Sdf.Path('/Recursive/D/B'), + Sdf.Path('/Recursive/D/C'), + Sdf.Path('/Recursive/D/D'), + }, + ) + + self.assertEqual( + set( + recursiveA.FindAllRelationshipTargetPaths( + recurseOnTargets=True, + predicate=lambda rel: rel.GetPrim().GetParent().GetName() + == 'Recursive' + or rel.GetPrim().GetName() in ('A', 'C'), + ) + ), + { + Sdf.Path('/Recursive/A'), + Sdf.Path('/Recursive/B'), + Sdf.Path('/Recursive/C'), + Sdf.Path('/Recursive/D'), + Sdf.Path('/Recursive/D/B'), + Sdf.Path('/Recursive/D/D'), + }, + ) def test_TargetsInInstances(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestTargetsInInstances.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestTargetsInInstances.{fmt}') s.GetRootLayer().ImportFromString('''#usda 1.0 def Scope "Ref" { @@ -277,8 +323,7 @@ def Scope "Root" ( def test_TargetsToObjectsInInstances(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory( - 'TestTargetsToObjectsInInstances.'+fmt) + stage = Usd.Stage.CreateInMemory(f'TestTargetsToObjectsInInstances.{fmt}') stage.GetRootLayer().ImportFromString('''#usda 1.0 def "Instance" { @@ -526,7 +571,7 @@ def _TestRelationshipForwarding(rel): def test_AuthoringTargets(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory("testAuthoringTargets." + fmt) + stage = Usd.Stage.CreateInMemory(f"testAuthoringTargets.{fmt}") prim = stage.DefinePrim("/Test") rel = prim.CreateRelationship("rel") diff --git a/pxr/usd/lib/usd/testenv/testUsdSpecializes.py b/pxr/usd/lib/usd/testenv/testUsdSpecializes.py index 974aa0974b3..31dae3e9c08 100644 --- a/pxr/usd/lib/usd/testenv/testUsdSpecializes.py +++ b/pxr/usd/lib/usd/testenv/testUsdSpecializes.py @@ -25,12 +25,12 @@ import unittest from pxr import Usd, Pcp, Sdf, Tf -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] class TestUsdSpecializes(unittest.TestCase): def test_BasicApi(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory("x."+fmt) + stage = Usd.Stage.CreateInMemory(f"x.{fmt}") specA = stage.DefinePrim("/SpecA") concrete = stage.OverridePrim("/Concrete") items = None @@ -64,13 +64,13 @@ def test_BasicApi(self): def test_SpecializedPrim(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory("x."+fmt) + stage = Usd.Stage.CreateInMemory(f"x.{fmt}") specA = stage.CreateClassPrim("/SpecA") stage.DefinePrim("/SpecA/Child") concrete = stage.DefinePrim("/Concrete") - assert not concrete.GetChildren() + assert not concrete.GetChildren() assert concrete.GetSpecializes().AddSpecialize(specA.GetPath()) self.assertEqual(concrete.GetChildren()[0].GetPath(), @@ -81,8 +81,8 @@ def test_SpecializedPrim(self): def test_SpecializesPathMapping(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory("x."+fmt, sessionLayer=None) - + stage = Usd.Stage.CreateInMemory(f"x.{fmt}", sessionLayer=None) + # Create test scenegraph stage.DefinePrim("/Ref") stage.DefinePrim("/Ref/Class") @@ -110,13 +110,13 @@ def test_SpecializesPathMapping(self): # Add a specializes path to the instance prim pointing to the # class prim. instancePrim.GetSpecializes() \ - .AddSpecialize("/Model/Class", Usd.ListPositionFrontOfPrependList) + .AddSpecialize("/Model/Class", Usd.ListPositionFrontOfPrependList) expectedSpecializePaths = Sdf.PathListOp() expectedSpecializePaths.prependedItems = [Sdf.Path("/Ref/Class")] instancePrimSpec = \ - stage.GetRootLayer().GetPrimAtPath("/Ref/Instance") + stage.GetRootLayer().GetPrimAtPath("/Ref/Instance") self.assertEqual(instancePrimSpec.GetInfo("specializes"), expectedSpecializePaths) @@ -130,7 +130,7 @@ def test_SpecializesPathMapping(self): # Add a global specialize path. instancePrim.GetSpecializes() \ - .AddSpecialize("/Class", Usd.ListPositionFrontOfPrependList) + .AddSpecialize("/Class", Usd.ListPositionFrontOfPrependList) expectedSpecializePaths = Sdf.PathListOp() expectedSpecializePaths.prependedItems = [Sdf.Path("/Class")] @@ -151,7 +151,7 @@ def test_SpecializesPathMapping(self): # map across the reference edit target. with self.assertRaises(Tf.ErrorException): instancePrim.GetSpecializes() \ - .AddSpecialize("/Ref2/Class", Usd.ListPositionFrontOfPrependList) + .AddSpecialize("/Ref2/Class", Usd.ListPositionFrontOfPrependList) self.assertEqual(instancePrimSpec.GetInfo("specializes"), expectedSpecializePaths) @@ -163,7 +163,7 @@ def test_SpecializesPathMapping(self): self.assertEqual(instancePrimSpec.GetInfo("specializes"), expectedSpecializePaths) - + # Set specialize paths using the SetSpecializes API instancePrim.GetSpecializes().SetSpecializes( ["/Model/Class", "/Class"]) @@ -183,7 +183,7 @@ def test_SpecializesPathMapping(self): def test_SpecializesPathMappingVariants(self): for fmt in allFormats: - stage = Usd.Stage.CreateInMemory("x."+fmt, sessionLayer=None) + stage = Usd.Stage.CreateInMemory(f"x.{fmt}", sessionLayer=None) # Create test scenegraph with variant refPrim = stage.DefinePrim("/Root") @@ -204,7 +204,7 @@ def test_SpecializesPathMappingVariants(self): # Check that authored specializes path does *not* include variant # selection. instancePrimSpec = \ - stage.GetRootLayer().GetPrimAtPath("/Root{v=x}Instance") + stage.GetRootLayer().GetPrimAtPath("/Root{v=x}Instance") expectedSpecializes = Sdf.PathListOp() expectedSpecializes.prependedItems = [Sdf.Path("/Root/Class")] self.assertEqual(instancePrimSpec.GetInfo('specializes'), diff --git a/pxr/usd/lib/usd/testenv/testUsdStage.py b/pxr/usd/lib/usd/testenv/testUsdStage.py index 71e181c6649..88260b0fa43 100644 --- a/pxr/usd/lib/usd/testenv/testUsdStage.py +++ b/pxr/usd/lib/usd/testenv/testUsdStage.py @@ -25,12 +25,12 @@ import sys, unittest from pxr import Sdf,Usd,Tf -allFormats = ['usd' + c for c in 'ac'] +allFormats = [f'usd{c}' for c in 'ac'] class TestUsdStage(unittest.TestCase): def test_UsedLayers(self): for fmt in allFormats: - sMain = Usd.Stage.CreateInMemory('testUsedLayers.'+fmt) + sMain = Usd.Stage.CreateInMemory(f'testUsedLayers.{fmt}') # includes a session layer... assert len(sMain.GetUsedLayers()) == 2 @@ -44,7 +44,7 @@ def test_UsedLayers(self): # Now make a layer that is only referenced in one # variant of a variantSet - sVar = Usd.Stage.CreateInMemory('testUsedLayers-sVar.'+fmt) + sVar = Usd.Stage.CreateInMemory(f'testUsedLayers-sVar.{fmt}') lVar = sVar.GetRootLayer() varPrim = sVar.DefinePrim('/varPrim') sVar.SetDefaultPrim(varPrim) @@ -60,35 +60,35 @@ def test_UsedLayers(self): assert len(usedLayers) == 4 assert lVar in usedLayers - fooSet.SetVariantSelection('default') + fooSet.SetVariantSelection('default') usedLayers = sMain.GetUsedLayers() assert len(usedLayers) == 3 - assert not (lVar in usedLayers) + assert lVar not in usedLayers def test_MutedLocalLayers(self): for fmt in allFormats: - sublayer_1 = Sdf.Layer.CreateNew('localLayers_sublayer_1.'+fmt) + sublayer_1 = Sdf.Layer.CreateNew(f'localLayers_sublayer_1.{fmt}') primSpec_1 = Sdf.CreatePrimInLayer(sublayer_1, '/A') attrSpec_1 = Sdf.AttributeSpec(primSpec_1, 'attr', Sdf.ValueTypeNames.String, declaresCustom = True) attrSpec_1.default = 'from_sublayer_1' - sublayer_2 = Sdf.Layer.CreateNew('localLayers_sublayer_2.'+fmt) + sublayer_2 = Sdf.Layer.CreateNew(f'localLayers_sublayer_2.{fmt}') primSpec_2 = Sdf.CreatePrimInLayer(sublayer_2, '/A') attrSpec_2 = Sdf.AttributeSpec(primSpec_2, 'attr', Sdf.ValueTypeNames.String, declaresCustom = True) attrSpec_2.default = 'from_sublayer_2' - - sessionLayer = Sdf.Layer.CreateNew('localLayers_session.'+fmt) + + sessionLayer = Sdf.Layer.CreateNew(f'localLayers_session.{fmt}') primSpec_session = Sdf.CreatePrimInLayer(sessionLayer, '/A') attrSpec_session = Sdf.AttributeSpec(primSpec_session, 'attr', Sdf.ValueTypeNames.String, declaresCustom = True) attrSpec_session.default = 'from_session' - rootLayer = Sdf.Layer.CreateNew('localLayers_root.'+fmt) + rootLayer = Sdf.Layer.CreateNew(f'localLayers_root.{fmt}') rootLayer.subLayerPaths = [sublayer_1.identifier, sublayer_2.identifier] stage = Usd.Stage.Open(rootLayer, sessionLayer) @@ -102,8 +102,12 @@ def test_MutedLocalLayers(self): stage.MuteLayer(rootLayer.identifier) assert attr.Get() == 'from_session' - assert (set(stage.GetUsedLayers()) == - set([sublayer_1, sublayer_2, sessionLayer, rootLayer])) + assert set(stage.GetUsedLayers()) == { + sublayer_1, + sublayer_2, + sessionLayer, + rootLayer, + } assert set(stage.GetMutedLayers()) == set([]) assert not stage.IsLayerMuted(sublayer_1.identifier) assert not stage.IsLayerMuted(sublayer_2.identifier) @@ -112,9 +116,8 @@ def test_MutedLocalLayers(self): stage.MuteLayer(sessionLayer.identifier) assert attr.Get() == 'from_sublayer_1' - assert (set(stage.GetUsedLayers()) == - set([sublayer_1, sublayer_2, rootLayer])) - assert set(stage.GetMutedLayers()) == set([sessionLayer.identifier]) + assert set(stage.GetUsedLayers()) == {sublayer_1, sublayer_2, rootLayer} + assert set(stage.GetMutedLayers()) == {sessionLayer.identifier} assert not stage.IsLayerMuted(sublayer_1.identifier) assert not stage.IsLayerMuted(sublayer_2.identifier) assert stage.IsLayerMuted(sessionLayer.identifier) @@ -122,19 +125,20 @@ def test_MutedLocalLayers(self): stage.MuteLayer(sublayer_1.identifier) assert attr.Get() == 'from_sublayer_2' - assert set(stage.GetUsedLayers()) == set([sublayer_2, rootLayer]) - assert (set(stage.GetMutedLayers()) == - set([sessionLayer.identifier, sublayer_1.identifier])) + assert set(stage.GetUsedLayers()) == {sublayer_2, rootLayer} + assert set(stage.GetMutedLayers()) == { + sessionLayer.identifier, + sublayer_1.identifier, + } assert stage.IsLayerMuted(sublayer_1.identifier) assert not stage.IsLayerMuted(sublayer_2.identifier) assert stage.IsLayerMuted(sessionLayer.identifier) assert not stage.IsLayerMuted(rootLayer.identifier) - + stage.UnmuteLayer(sessionLayer.identifier) assert attr.Get() == 'from_session' - assert (set(stage.GetUsedLayers()) == - set([sublayer_2, sessionLayer, rootLayer])) - assert set(stage.GetMutedLayers()) == set([sublayer_1.identifier]) + assert set(stage.GetUsedLayers()) == {sublayer_2, sessionLayer, rootLayer} + assert set(stage.GetMutedLayers()) == {sublayer_1.identifier} assert stage.IsLayerMuted(sublayer_1.identifier) assert not stage.IsLayerMuted(sublayer_2.identifier) assert not stage.IsLayerMuted(sessionLayer.identifier) @@ -144,9 +148,11 @@ def test_MutedLocalLayers(self): sublayer_2.identifier], [sublayer_1.identifier]) assert attr.Get() == 'from_sublayer_1' - assert set(stage.GetUsedLayers()) == set([sublayer_1, rootLayer]) - assert (set(stage.GetMutedLayers()) == - set([sublayer_2.identifier, sessionLayer.identifier])) + assert set(stage.GetUsedLayers()) == {sublayer_1, rootLayer} + assert set(stage.GetMutedLayers()) == { + sublayer_2.identifier, + sessionLayer.identifier, + } assert not stage.IsLayerMuted(sublayer_1.identifier) assert stage.IsLayerMuted(sublayer_2.identifier) assert stage.IsLayerMuted(sessionLayer.identifier) @@ -154,18 +160,18 @@ def test_MutedLocalLayers(self): def test_MutedReferenceLayers(self): for fmt in allFormats: - sublayer_1 = Sdf.Layer.CreateNew('refLayers_sublayer_1.'+fmt) + sublayer_1 = Sdf.Layer.CreateNew(f'refLayers_sublayer_1.{fmt}') primSpec_1 = Sdf.CreatePrimInLayer(sublayer_1, '/A') attrSpec_1 = Sdf.AttributeSpec(primSpec_1, 'attr', Sdf.ValueTypeNames.String, declaresCustom = True) attrSpec_1.default = 'from_sublayer_1' - refLayer = Sdf.Layer.CreateNew('refLayers_ref.'+fmt) + refLayer = Sdf.Layer.CreateNew(f'refLayers_ref.{fmt}') primSpec_ref = Sdf.CreatePrimInLayer(refLayer, '/A') refLayer.subLayerPaths = [sublayer_1.identifier] - rootLayer = Sdf.Layer.CreateNew('refLayers_root.'+fmt) + rootLayer = Sdf.Layer.CreateNew(f'refLayers_root.{fmt}') primSpec_root = Sdf.CreatePrimInLayer(rootLayer, '/A') primSpec_root.referenceList.Add( Sdf.Reference(refLayer.identifier, '/A')) @@ -176,25 +182,23 @@ def test_MutedReferenceLayers(self): assert attr assert attr.Get() == 'from_sublayer_1' - assert (set(stage.GetUsedLayers()) == - set([sublayer_1, refLayer, rootLayer])) + assert set(stage.GetUsedLayers()) == {sublayer_1, refLayer, rootLayer} assert set(stage.GetMutedLayers()) == set([]) assert not stage.IsLayerMuted(sublayer_1.identifier) assert not stage.IsLayerMuted(refLayer.identifier) assert not stage.IsLayerMuted(rootLayer.identifier) stage.MuteLayer(sublayer_1.identifier) - assert attr.Get() == None - assert set(stage.GetUsedLayers()) == set([refLayer, rootLayer]) - assert set(stage.GetMutedLayers()) == set([sublayer_1.identifier]) + assert attr.Get() is None + assert set(stage.GetUsedLayers()) == {refLayer, rootLayer} + assert set(stage.GetMutedLayers()) == {sublayer_1.identifier} assert stage.IsLayerMuted(sublayer_1.identifier) assert not stage.IsLayerMuted(refLayer.identifier) assert not stage.IsLayerMuted(rootLayer.identifier) stage.UnmuteLayer(sublayer_1.identifier) assert attr.Get() == 'from_sublayer_1' - assert (set(stage.GetUsedLayers()) == - set([sublayer_1, refLayer, rootLayer])) + assert set(stage.GetUsedLayers()) == {sublayer_1, refLayer, rootLayer} assert set(stage.GetMutedLayers()) == set([]) assert not stage.IsLayerMuted(sublayer_1.identifier) assert not stage.IsLayerMuted(refLayer.identifier) @@ -202,17 +206,17 @@ def test_MutedReferenceLayers(self): stage.MuteLayer(refLayer.identifier) assert not attr - assert set(stage.GetUsedLayers()) == set([rootLayer]) - assert set(stage.GetMutedLayers()) == set([refLayer.identifier]) + assert set(stage.GetUsedLayers()) == {rootLayer} + assert set(stage.GetMutedLayers()) == {refLayer.identifier} assert not stage.IsLayerMuted(sublayer_1.identifier) assert stage.IsLayerMuted(refLayer.identifier) assert not stage.IsLayerMuted(rootLayer.identifier) stage.MuteAndUnmuteLayers([sublayer_1.identifier], [refLayer.identifier]) - assert attr.Get() == None - assert set(stage.GetUsedLayers()) == set([refLayer, rootLayer]) - assert set(stage.GetMutedLayers()) == set([sublayer_1.identifier]) + assert attr.Get() is None + assert set(stage.GetUsedLayers()) == {refLayer, rootLayer} + assert set(stage.GetMutedLayers()) == {sublayer_1.identifier} assert stage.IsLayerMuted(sublayer_1.identifier) assert not stage.IsLayerMuted(refLayer.identifier) assert not stage.IsLayerMuted(rootLayer.identifier) @@ -220,15 +224,15 @@ def test_MutedReferenceLayers(self): def test_UsdStageIsSupportedFile(self): validFileNames = ['foo.usda', '/baz/bar/foo.usd', 'foo.usd', 'xxx.usdc'] invalidFileNames = ['hello.alembic', 'hello.usdx', 'ill.never.work'] - assert all([Usd.Stage.IsSupportedFile(fl) for fl in validFileNames]) - assert not all([Usd.Stage.IsSupportedFile(fl) for fl in invalidFileNames]) + assert all(Usd.Stage.IsSupportedFile(fl) for fl in validFileNames) + assert not all(Usd.Stage.IsSupportedFile(fl) for fl in invalidFileNames) def test_testUsdStageColorConfiguration(self): for fmt in allFormats: - f = lambda base: base + '.' + fmt + f = lambda base: f'{base}.{fmt}' rootLayer = Sdf.Layer.CreateNew(f("colorConf"), f("colorConf")) stage = Usd.Stage.Open(rootLayer) - + colorConfigFallbacks = Usd.Stage.GetColorConfigFallbacks() assert len(colorConfigFallbacks) == 2 fallbackColorConfiguration = colorConfigFallbacks[0] @@ -242,7 +246,7 @@ def test_testUsdStageColorConfiguration(self): colorConfig = Sdf.AssetPath("https://github.com/imageworks/OpenColorIO-Configs/blob/master/aces_1.0.3/config.ocio") stage.SetColorConfiguration(colorConfig) self.assertEqual(stage.GetColorConfiguration(), colorConfig) - + # Need to drop down to sdf API to clear color configuration values. stage.GetRootLayer().ClearColorConfiguration() self.assertEqual(stage.GetColorConfiguration(), @@ -261,7 +265,7 @@ def test_testUsdStageColorConfiguration(self): # in for it. self.assertEqual(stage.GetColorManagementSystem(), fallbackColorManagementSystem) - + # Test colorSpace metadata. # Note: this is here an not in a testUsdAttribute* because this # API on UsdAttribute pertains to encoding of color spaces, which @@ -279,7 +283,7 @@ def test_testUsdStageColorConfiguration(self): def test_UsdStageTimeMetadata(self): for fmt in allFormats: - f = lambda base: base + '.' + fmt + f = lambda base: f'{base}.{fmt}' sessionLayer = Sdf.Layer.CreateNew(f('sessionLayer'), f('sessionLayer')) rootLayer = Sdf.Layer.CreateNew(f("rootLayer"), f("rootLayer")) @@ -384,9 +388,9 @@ def test_UsdStageTimeMetadata(self): def test_BadGetPrimAtPath(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('testBadGetPrimAtPath.'+fmt) + s = Usd.Stage.CreateInMemory(f'testBadGetPrimAtPath.{fmt}') s.DefinePrim('/Foo') - + # Should get an invalid prim when using a relative path, even # if a root prim with that name exists. assert(not s.GetPrimAtPath('Foo')) @@ -401,17 +405,17 @@ def test_BadGetPrimAtPath(self): def test_Save(self): for fmt in allFormats: def _CreateLayers(rootLayerName): - f = lambda base: base + '.' + fmt + f = lambda base: f'{base}.{fmt}' rootLayer = Sdf.Layer.CreateNew(f(rootLayerName)) - subLayer = Sdf.Layer.CreateNew(f(rootLayerName + '_sublayer')) - anonLayer = Sdf.Layer.CreateAnonymous(f(rootLayerName + '_anon')) - refLayer = Sdf.Layer.CreateNew(f(rootLayerName + '_reflayer')) + subLayer = Sdf.Layer.CreateNew(f(f'{rootLayerName}_sublayer')) + anonLayer = Sdf.Layer.CreateAnonymous(f(f'{rootLayerName}_anon')) + refLayer = Sdf.Layer.CreateNew(f(f'{rootLayerName}_reflayer')) # Author some scene description so all layers start as dirty. rootLayer.subLayerPaths.append(subLayer.identifier) rootLayer.subLayerPaths.append(anonLayer.identifier) - primPath = "/" + rootLayerName + primPath = f"/{rootLayerName}" subLayerPrim = Sdf.CreatePrimInLayer(subLayer, primPath) subLayerPrim.referenceList.Add( Sdf.Reference(refLayer.identifier, primPath)) @@ -425,39 +429,73 @@ def _CreateLayers(rootLayerName): # local session layers. The layer referenced from the session # layer is also saved, which is as intended. (rootLayer, rootSubLayer, rootAnonLayer, rootRefLayer) = \ - _CreateLayers('root') + _CreateLayers('root') (sessionLayer, sessionSubLayer, sessionAnonLayer, sessionRefLayer) = \ - _CreateLayers('session') + _CreateLayers('session') stage = Usd.Stage.Open(rootLayer, sessionLayer) - assert all([l.dirty for l in - [rootLayer, rootSubLayer, rootAnonLayer, rootRefLayer, - sessionLayer, sessionSubLayer, sessionAnonLayer, - sessionRefLayer]]) + assert all( + l.dirty + for l in [ + rootLayer, + rootSubLayer, + rootAnonLayer, + rootRefLayer, + sessionLayer, + sessionSubLayer, + sessionAnonLayer, + sessionRefLayer, + ] + ) stage.Save() - assert not any([l.dirty for l in - [rootLayer, rootSubLayer, rootRefLayer, - sessionRefLayer]]) - assert all([l.dirty for l in [rootAnonLayer, sessionLayer, - sessionSubLayer, sessionAnonLayer]]) + assert not any( + l.dirty + for l in [rootLayer, rootSubLayer, rootRefLayer, sessionRefLayer] + ) + assert all( + l.dirty + for l in [ + rootAnonLayer, + sessionLayer, + sessionSubLayer, + sessionAnonLayer, + ] + ) # After calling Usd.Stage.SaveSessionLayers(), only the local session # layers should be saved. (rootLayer, rootSubLayer, rootAnonLayer, rootRefLayer) = \ - _CreateLayers('root_2') + _CreateLayers('root_2') (sessionLayer, sessionSubLayer, sessionAnonLayer, sessionRefLayer) = \ - _CreateLayers('session_2') + _CreateLayers('session_2') stage = Usd.Stage.Open(rootLayer, sessionLayer) - assert all([l.dirty for l in - [rootLayer, rootSubLayer, rootAnonLayer, rootRefLayer, - sessionLayer, sessionSubLayer, sessionAnonLayer, - sessionRefLayer]]) + assert all( + l.dirty + for l in [ + rootLayer, + rootSubLayer, + rootAnonLayer, + rootRefLayer, + sessionLayer, + sessionSubLayer, + sessionAnonLayer, + sessionRefLayer, + ] + ) stage.SaveSessionLayers() - assert all([l.dirty for l in - [rootLayer, rootSubLayer, rootAnonLayer, rootRefLayer, - sessionAnonLayer, sessionRefLayer]]) - assert not any([l.dirty for l in [sessionLayer, sessionSubLayer]]) + assert all( + l.dirty + for l in [ + rootLayer, + rootSubLayer, + rootAnonLayer, + rootRefLayer, + sessionAnonLayer, + sessionRefLayer, + ] + ) + assert not any(l.dirty for l in [sessionLayer, sessionSubLayer]) if __name__ == "__main__": unittest.main() diff --git a/pxr/usd/lib/usd/testenv/testUsdStageLoadUnload.py b/pxr/usd/lib/usd/testenv/testUsdStageLoadUnload.py index 6374d9eb8ae..6bd1687a06e 100644 --- a/pxr/usd/lib/usd/testenv/testUsdStageLoadUnload.py +++ b/pxr/usd/lib/usd/testenv/testUsdStageLoadUnload.py @@ -25,7 +25,7 @@ import os, sys, tempfile, unittest from pxr import Gf, Tf, Sdf, Usd -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] class PayloadedScene(object): def __init__(self, fmt, unload=True, loadSet=Usd.Stage.LoadAll, @@ -41,26 +41,26 @@ def __init__(self, fmt, unload=True, loadSet=Usd.Stage.LoadAll, # /Foo/Baz ---(P)---> /Baz payload3.fmt # /Baz/Garply ---(P)---> /Garply # /Garply/Qux - - ext = '.'+fmt + + ext = f'.{fmt}' # Create payload1.fmt - self.__payload1 = stageCreateFn("payload1"+ext) + self.__payload1 = stageCreateFn(f"payload1{ext}") p = self.__payload1.DefinePrim("/Sad/Panda", "Scope") # Create payload3.usda - self.__payload3 = stageCreateFn("payload3"+ext) + self.__payload3 = stageCreateFn(f"payload3{ext}") p = self.__payload3.DefinePrim("/Garply/Qux", "Scope") # Create payload2.usda - self.__payload2 = stageCreateFn("payload2"+ext) + self.__payload2 = stageCreateFn(f"payload2{ext}") p = self.__payload2.DefinePrim("/Baz/Garply", "Scope") p.SetPayload(self.__payload3.GetRootLayer(), "/Garply") # # Create the scene that references payload1 and payload2 # - self.stage = stageCreateFn("scene"+ext, loadSet) + self.stage = stageCreateFn(f"scene{ext}", loadSet) p = self.stage.DefinePrim("/Sad", "Scope") p.SetPayload(self.__payload1.GetRootLayer(), "/Sad") @@ -74,18 +74,18 @@ def __init__(self, fmt, unload=True, loadSet=Usd.Stage.LoadAll, def CleanupOnDiskAssets(self, fmt): import os - + del self.stage del self.__payload1 del self.__payload2 del self.__payload3 - ext = "." + fmt + ext = f".{fmt}" for i in [1,2,3]: - fname = "payload" + str(i) + ext + fname = f"payload{str(i)}{ext}" if os.path.exists(fname): os.unlink(fname) - fname = "scene"+ ext + fname = f"scene{ext}" if os.path.exists(fname): os.unlink(fname) @@ -461,7 +461,7 @@ def test_StageCreateNew(self): """Tests the behavior of Usd.Stage.Create """ for fmt in allFormats: - layerName = "testLayer." + fmt + layerName = f"testLayer.{fmt}" if os.path.exists(layerName): os.unlink(layerName) @@ -509,7 +509,7 @@ def test_StageReload(self): # Try with a real file -- saved changes preserved, unsaved changes get # discarded. def _TestStageReload(fmt): - with tempfile.NamedTemporaryFile(suffix='.%s' % fmt) as f: + with tempfile.NamedTemporaryFile(suffix=f'.{fmt}') as f: f.close() s = Usd.Stage.CreateNew(f.name) @@ -543,8 +543,7 @@ def test_StageLayerReload(self): def _TestLayerReload(fmt): # First, test case where the reloaded layer is in the # stage's root LayerStack. - with tempfile.NamedTemporaryFile(suffix='.%s' % fmt) as l1name, \ - tempfile.NamedTemporaryFile(suffix='.%s' % fmt) as l2name: + with (tempfile.NamedTemporaryFile(suffix=f'.{fmt}') as l1name, tempfile.NamedTemporaryFile(suffix=f'.{fmt}') as l2name): l1name.close() l2name.close() @@ -567,7 +566,7 @@ def _TestLayerReload(fmt): assert not s.GetPrimAtPath('/foo') assert s.GetPrimAtPath('/bar') - + # NOTE: l1name will want to delete the underlying file # on __exit__ from the context manager. But stage s # may have the file open. If so the deletion will @@ -577,8 +576,7 @@ def _TestLayerReload(fmt): # Now test the case where the reloaded layer is in a referenced # LayerStack. - with tempfile.NamedTemporaryFile(suffix='.%s' % fmt) as rootLayerName, \ - tempfile.NamedTemporaryFile(suffix='.%s' % fmt) as refLayerName: + with (tempfile.NamedTemporaryFile(suffix=f'.{fmt}') as rootLayerName, tempfile.NamedTemporaryFile(suffix=f'.{fmt}') as refLayerName): rootLayerName.close() refLayerName.close() @@ -595,7 +593,7 @@ def _TestLayerReload(fmt): s = Usd.Stage.Open(rootLayerName.name) assert s.GetPrimAtPath('/foo/bar') - + del refLayer.GetPrimAtPath('/foo').nameChildren['bar'] refLayer.Export(refLayerName.name) Sdf.Layer.Find(refLayerName.name).Reload(force = True) @@ -615,7 +613,7 @@ def _TestLayerReload(fmt): # not the behavior we ultimately want -- see bug 102444. # Can't test Reload() for usdc on Windows because the system # won't allow us to modify the memory-mapped file. - if not (platform.system() == 'Windows' and fmt == 'usdc'): + if platform.system() != 'Windows' or fmt != 'usdc': _TestLayerReload(fmt) if __name__ == "__main__": diff --git a/pxr/usd/lib/usd/testenv/testUsdStagePopulationMasks.py b/pxr/usd/lib/usd/testenv/testUsdStagePopulationMasks.py index eb48d728d2f..ff8954d84cb 100644 --- a/pxr/usd/lib/usd/testenv/testUsdStagePopulationMasks.py +++ b/pxr/usd/lib/usd/testenv/testUsdStagePopulationMasks.py @@ -315,7 +315,7 @@ def test_Bug145873(self): # requested index paths in pcp. payload = Usd.Stage.CreateInMemory() for n in ('One', 'Two', 'Three'): - payload.DefinePrim('/CubesModel/Geom/Cube' + n) + payload.DefinePrim(f'/CubesModel/Geom/Cube{n}') root = Usd.Stage.CreateInMemory() cubes = root.DefinePrim('/Cubes') diff --git a/pxr/usd/lib/usd/testenv/testUsdTimeOffsets.py b/pxr/usd/lib/usd/testenv/testUsdTimeOffsets.py index a9c8a07a08d..21f1ef2a5ac 100644 --- a/pxr/usd/lib/usd/testenv/testUsdTimeOffsets.py +++ b/pxr/usd/lib/usd/testenv/testUsdTimeOffsets.py @@ -25,11 +25,7 @@ import sys, os, unittest from pxr import Sdf, Usd, Pcp, Vt, Tf, Gf -allFormats = ['usd' + x for x in 'ac'] - -# --------------------------------------------------------------------------- # -# Support code for generating & verifying offsets -# --------------------------------------------------------------------------- # +allFormats = [f'usd{x}' for x in 'ac'] class AdjustedPrim(object): """A convenience object for bundling up a prim,stage and offset. @@ -49,10 +45,7 @@ def MakePrim(stage, refLyr, path, offset, scale, matchPath=False): p.stage = stage p.layerOffset = Sdf.LayerOffset(offset, scale) - refPath = "/Foo" - if matchPath: - refPath = path - + refPath = path if matchPath else "/Foo" ref = Sdf.Reference(refLyr.identifier, refPath, p.layerOffset) assert p.prim.GetReferences().AddReference(ref) return p @@ -62,7 +55,7 @@ def GenTestLayer(testId, fmt): """Generates a layer with three time samples at 1.0, 2.0, and 10.0 at . """ - l = Sdf.Layer.CreateNew("sourceData-" + testId + "." + fmt) + l = Sdf.Layer.CreateNew(f"sourceData-{testId}.{fmt}") stage = Usd.Stage.Open(l) stage.OverridePrim("/Foo") @@ -224,9 +217,9 @@ def test_OffsetsAuthoring(self): # and we test authoring a time sample into the reference via an # EditTarget, as well as to the subLayer. In both cases we check that # the time value was correctly transformed. - rootLayer = Sdf.Layer.CreateAnonymous('root.'+fmt) - subLayer = Sdf.Layer.CreateAnonymous('sub.'+fmt) - refLayer = Sdf.Layer.CreateAnonymous('ref.'+fmt) + rootLayer = Sdf.Layer.CreateAnonymous(f'root.{fmt}') + subLayer = Sdf.Layer.CreateAnonymous(f'sub.{fmt}') + refLayer = Sdf.Layer.CreateAnonymous(f'ref.{fmt}') # add subLayer to rootLayer and give it a layer offset. subOffset = Sdf.LayerOffset(scale=3.0, offset=4.0) diff --git a/pxr/usd/lib/usd/testenv/testUsdValueClips.py b/pxr/usd/lib/usd/testenv/testUsdValueClips.py index bc5f3f92009..6c0aa3386d7 100644 --- a/pxr/usd/lib/usd/testenv/testUsdValueClips.py +++ b/pxr/usd/lib/usd/testenv/testUsdValueClips.py @@ -743,9 +743,9 @@ def test_ClipsCannotIntroduceNewTopology(self): def test_ClipAuthoring(self): """Tests clip authoring API on Usd.ClipsAPI""" - allFormats = ['usd' + x for x in 'ac'] + allFormats = [f'usd{x}' for x in 'ac'] for fmt in allFormats: - stage = Usd.Stage.CreateInMemory('TestClipAuthoring.'+fmt) + stage = Usd.Stage.CreateInMemory(f'TestClipAuthoring.{fmt}') prim = stage.DefinePrim('/Model') model = Usd.ClipsAPI(prim) @@ -804,7 +804,7 @@ def test_ClipAuthoring(self): model.SetClipTemplateEndTime(5) self.assertEqual(model.GetClipTemplateEndTime(), 5) - + # Ensure we can't set the clipTemplateStride to 0 with self.assertRaises(Tf.ErrorException) as e: model.SetClipTemplateStride(0) @@ -823,9 +823,9 @@ def test_ClipAuthoring(self): def test_ClipSetAuthoring(self): """Tests clip authoring API with clip sets on Usd.ClipsAPI""" - allFormats = ['usd' + x for x in 'ac'] + allFormats = [f'usd{x}' for x in 'ac'] for fmt in allFormats: - stage = Usd.Stage.CreateInMemory('TestClipSetAuthoring.'+fmt) + stage = Usd.Stage.CreateInMemory(f'TestClipSetAuthoring.{fmt}') prim = stage.DefinePrim('/Model') model = Usd.ClipsAPI(prim) @@ -895,7 +895,7 @@ def test_ClipSetAuthoring(self): model.SetClipTemplateEndTime(5, clipSetName) self.assertEqual(model.GetClipTemplateEndTime(clipSetName), 5) - + # Ensure we can't set the clipTemplateStride to 0 with self.assertRaises(Tf.ErrorException) as e: model.SetClipTemplateStride(0, clipSetName) diff --git a/pxr/usd/lib/usd/testenv/testUsdVariantEditing.py b/pxr/usd/lib/usd/testenv/testUsdVariantEditing.py index dd70c9fd31f..c1f8b91c597 100644 --- a/pxr/usd/lib/usd/testenv/testUsdVariantEditing.py +++ b/pxr/usd/lib/usd/testenv/testUsdVariantEditing.py @@ -26,15 +26,15 @@ from pxr import Gf, Tf, Sdf, Usd def OpenLayer(name): - layerFile = '%s.usda' % name + layerFile = f'{name}.usda' layer = Sdf.Layer.FindOrOpen(layerFile) - assert layer, 'failed to open layer @%s@' % layerFile + assert layer, f'failed to open layer @{layerFile}@' return layer # Open stage. layer = OpenLayer('testAPI_var') stage = Usd.Stage.Open(layer.identifier) -assert stage, 'failed to create stage for @%s@' % layer.identifier +assert stage, f'failed to create stage for @{layer.identifier}@' # Check GetLayerStack behavior. assert stage.GetLayerStack()[0] == stage.GetSessionLayer() diff --git a/pxr/usd/lib/usd/testenv/testUsdVariantFallbacks.py b/pxr/usd/lib/usd/testenv/testUsdVariantFallbacks.py index 6d392a32343..7692a927b81 100644 --- a/pxr/usd/lib/usd/testenv/testUsdVariantFallbacks.py +++ b/pxr/usd/lib/usd/testenv/testUsdVariantFallbacks.py @@ -36,18 +36,17 @@ def test_Basic(self): ['green']) def OpenLayer(name): - fullName = '%s.usda' % name + fullName = f'{name}.usda' layerFile = os.path.abspath(fullName) - self.assertTrue(layerFile, 'failed to find @%s@' % fullName) + self.assertTrue(layerFile, f'failed to find @{fullName}@') layer = Sdf.Layer.FindOrOpen(layerFile) - self.assertTrue(layer, 'failed to open layer @%s@' % fullName) + self.assertTrue(layer, f'failed to open layer @{fullName}@') return layer # Open stage. layer = OpenLayer('testAPI_var') stage = Usd.Stage.Open(layer.identifier) - self.assertTrue(stage, - 'failed to create stage for @%s@' % layer.identifier) + self.assertTrue(stage, f'failed to create stage for @{layer.identifier}@') sarah = stage.GetPrimAtPath('/Sarah') displayColor = sarah.GetVariantSet('displayColor') self.assertTrue(sarah, 'failed to find prim /Sarah') diff --git a/pxr/usd/lib/usd/testenv/testUsdVariants.py b/pxr/usd/lib/usd/testenv/testUsdVariants.py index 2c62088a15d..248b0c18930 100644 --- a/pxr/usd/lib/usd/testenv/testUsdVariants.py +++ b/pxr/usd/lib/usd/testenv/testUsdVariants.py @@ -25,7 +25,7 @@ import sys, os, unittest from pxr import Sdf, Usd, Tf -allFormats = ['usd' + x for x in 'ac'] +allFormats = [f'usd{x}' for x in 'ac'] class TestUsdVariants(unittest.TestCase): def test_VariantSetAPI(self): @@ -52,7 +52,7 @@ def test_VariantSetAPI(self): def test_VariantSelectionPathAbstraction(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestVariantSelectionPathAbstraction.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestVariantSelectionPathAbstraction.{fmt}') p = s.OverridePrim("/Foo") vss = p.GetVariantSets() self.assertFalse(p.HasVariantSets()) @@ -94,7 +94,7 @@ def test_VariantSelectionPathAbstraction(self): def test_NestedVariantSets(self): for fmt in allFormats: - s = Usd.Stage.CreateInMemory('TestNestedVariantSets.'+fmt) + s = Usd.Stage.CreateInMemory(f'TestNestedVariantSets.{fmt}') p = s.DefinePrim('/Foo', 'Scope') vss = p.GetVariantSets() vs_lod = vss.AddVariantSet("LOD") diff --git a/pxr/usd/lib/usd/usdGenSchema.py b/pxr/usd/lib/usd/usdGenSchema.py index 282a776fb12..dde39345a6b 100644 --- a/pxr/usd/lib/usd/usdGenSchema.py +++ b/pxr/usd/lib/usd/usdGenSchema.py @@ -69,18 +69,15 @@ def _GetDefiningLayerAndPrim(stage, schemaName): """ Searches the stage LayerStack for a prim whose name is equal to schemaName. """ - # SchemaBase is not actually defined in the core schema file, but this - # behavior causes the code generator to produce correct C++ inheritance. if schemaName == 'SchemaBase': return (stage.GetLayerStack()[-1], None) - - else: - for layer in stage.GetLayerStack(): - for sdfPrim in layer.rootPrims: - if sdfPrim.name == schemaName: - return (layer, sdfPrim) - raise Exception("Could not find the defining layer for schema: %s" % schemaName) + for layer in stage.GetLayerStack(): + for sdfPrim in layer.rootPrims: + if sdfPrim.name == schemaName: + return (layer, sdfPrim) + + raise Exception(f"Could not find the defining layer for schema: {schemaName}") def _GetLibMetadata(layer): @@ -168,11 +165,10 @@ def _CamelCase(aString): """Returns the given string (camelCase or ProperCase) in camelCase, stripping out any non-alphanumeric characters. """ - if len(aString) > 1: - pcase = _ProperCase(aString) - return pcase[0].lower() + pcase[1:] - else: + if len(aString) <= 1: return aString.lower() + pcase = _ProperCase(aString) + return pcase[0].lower() + pcase[1:] Token = namedtuple('Token', ['id', 'value', 'desc']) @@ -197,7 +193,7 @@ def __init__(self, sdfProp): self.apiName = self.customData.get('apiName', self.name) self.apiGet = self.customData.get('apiGetImplementation', self.CodeGen.Generated) if self.apiGet not in [self.CodeGen.Generated, self.CodeGen.Custom]: - print ("Token '%s' is not valid." % self.apiGet) + print(f"Token '{self.apiGet}' is not valid.") self.rawName = sdfProp.name self.doc = _SanitizeDoc(sdfProp.documentation, '\n /// ') self.custom = sdfProp.custom @@ -218,13 +214,12 @@ class AttrInfo(PropInfo): def __init__(self, sdfProp): super(AttrInfo, self).__init__(sdfProp) self.allowedTokens = sdfProp.GetInfo('allowedTokens') - + self.variability = str(sdfProp.variability).replace('Sdf.', 'Sdf') self.fallback = sdfProp.default self.cppType = sdfProp.typeName.cppTypeName - self.usdType = "SdfValueTypeNames->%s" % ( - valueTypeNameToStr[sdfProp.typeName]) - + self.usdType = f"SdfValueTypeNames->{valueTypeNameToStr[sdfProp.typeName]}" + self.details = [('C++ Type', self.cppType), ('Usd Type', self.usdType), ('Variability', self.variability), @@ -232,8 +227,8 @@ def __init__(self, sdfProp): if self.fallback is None else str(self.fallback))] if self.allowedTokens: self.details.append(('\\ref ' + \ - _GetTokensPrefix(sdfProp.layer) + \ - 'Tokens "Allowed Values"', str(self.allowedTokens))) + _GetTokensPrefix(sdfProp.layer) + \ + 'Tokens "Allowed Values"', str(self.allowedTokens))) def _ExtractNames(sdfPrim, customData): usdPrimTypeName = sdfPrim.path.name @@ -261,27 +256,27 @@ def _FindAllInherits(p): class ClassInfo(object): def __init__(self, usdPrim, sdfPrim): - # Error handling - errorPrefix = ('Invalid schema definition at ' - + '<' + str(sdfPrim.path) + '>') errorSuffix = ('See ' 'https://graphics.pixar.com/usd/docs/api/' '_usd__page__generating_schemas.html ' 'for more information.\n') + errorPrefix = ( + 'Invalid schema definition at ' + '<' + str(sdfPrim.path) + '>' + ) errorMsg = lambda s: errorPrefix + '\n' + s + '\n' + errorSuffix # First validate proper class naming... - if (sdfPrim.typeName != sdfPrim.path.name and - sdfPrim.typeName != ''): - raise Exception(errorMsg("Code generation requires that every instantiable " - "class's name must match its declared type " - "('%s' and '%s' do not match.)" % - (sdfPrim.typeName, sdfPrim.path.name))) - + if sdfPrim.typeName not in [sdfPrim.path.name, '']: + raise Exception( + errorMsg( + f"Code generation requires that every instantiable class's name must match its declared type ('{sdfPrim.typeName}' and '{sdfPrim.path.name}' do not match.)" + ) + ) + # NOTE: usdPrim should ONLY be used for querying information regarding # the class's parent in order to avoid duplicating class members during # code generation. - inherits = usdPrim.GetMetadata('inheritPaths') + inherits = usdPrim.GetMetadata('inheritPaths') inheritsList = _ListOpToList(inherits) # We do not allow multiple inheritance @@ -323,7 +318,7 @@ def __init__(self, usdPrim, sdfPrim): parentCustomData = dict(parentPrim.customData) (parentUsdName, parentClassName, self.parentCppClassName, self.parentBaseFileName) = \ - _ExtractNames(parentPrim, parentCustomData) + _ExtractNames(parentPrim, parentCustomData) # Only Typed and APISchemaBase are allowed to have no inherits, since # these are the core base types for all the typed and API schemas # respectively. @@ -348,12 +343,12 @@ def __init__(self, usdPrim, sdfPrim): self.isAPISchemaBase = self.cppClassName == 'UsdAPISchemaBase' self.isApi = not self.isTyped and not self.isConcrete and \ - not self.isAPISchemaBase + not self.isAPISchemaBase self.apiSchemaType = self.customData.get(Usd.Tokens.apiSchemaType, Usd.Tokens.singleApply if self.isApi else None) if self.isApi and \ - self.apiSchemaType not in [Usd.Tokens.nonApplied, + self.apiSchemaType not in [Usd.Tokens.nonApplied, Usd.Tokens.singleApply, Usd.Tokens.multipleApply]: raise Exception(errorMsg("CustomData 'apiSchemaType' is %s. It must" @@ -372,16 +367,16 @@ def __init__(self, usdPrim, sdfPrim): 'nor provide a typename(API).')) if self.isApi and sdfPrim.path.name != "APISchemaBase" and \ - not sdfPrim.path.name.endswith('API'): + not sdfPrim.path.name.endswith('API'): raise Exception(errorMsg('API schemas must be named with an API suffix.')) - + if self.isApi and not self.isAppliedAPISchema and self.isPrivateApply: raise Exception(errorMsg("Non-applied API schema cannot be tagged " "as private-apply")) if self.isApi and sdfPrim.path.name != "APISchemaBase" and \ - (not self.parentCppClassName): + (not self.parentCppClassName): raise Exception(errorMsg("API schemas must explicitly inherit from " "UsdAPISchemaBase.")) @@ -390,23 +385,23 @@ def __init__(self, usdPrim, sdfPrim): 'apiSchemaType value.')) if (not self.isApi or not self.isAppliedAPISchema) and \ - self.isPrivateApply: + self.isPrivateApply: raise Exception(errorMsg('Non API schemas or non-applied API ' 'schemas cannot be marked with ' 'isPrivateApply, only applied API schemas ' 'have an Apply() method generated. ')) def GetHeaderFile(self): - return self.baseFileName + '.h' + return f'{self.baseFileName}.h' def GetParentHeaderFile(self): - return self.parentBaseFileName + '.h' + return f'{self.parentBaseFileName}.h' def GetCppFile(self): - return self.baseFileName + '.cpp' + return f'{self.baseFileName}.cpp' def GetWrapFile(self): - return 'wrap' + self.className + '.cpp' + return f'wrap{self.className}.cpp' #------------------------------------------------------------------------------# @@ -438,18 +433,14 @@ def _ValidateFields(spec): return False def GetClassInfo(classes, cppClassName): - for c in classes: - if c.cppClassName == cppClassName: - return c - return None + return next((c for c in classes if c.cppClassName == cppClassName), None) def ParseUsd(usdFilePath): sdfLayer = Sdf.Layer.FindOrOpen(usdFilePath) stage = Usd.Stage.Open(sdfLayer) - classes = [] - hasInvalidFields = False + classes = [] # PARSE CLASSES for sdfPrim in sdfLayer.rootPrims: if sdfPrim.name == "Typed" or sdfPrim.specifier != Sdf.SpecifierClass: @@ -480,80 +471,69 @@ def ParseUsd(usdFilePath): # Assert unique attribute names if attrInfo.name in classInfo.attrs: raise Exception( - 'Schema Attribute names must be unique, ' - 'irrespective of namespacing. ' - 'Duplicate name encountered: %s.%s' % - (classInfo.usdPrimTypeName, attrInfo.name)) + f'Schema Attribute names must be unique, irrespective of namespacing. Duplicate name encountered: {classInfo.usdPrimTypeName}.{attrInfo.name}' + ) elif attrInfo.apiName in attrApiNames: raise Exception( - 'Schema Attribute API names must be unique. ' - 'Duplicate apiName encountered: %s.%s' % - (classInfo.usdPrimTypeName, attrInfo.apiName)) + f'Schema Attribute API names must be unique. Duplicate apiName encountered: {classInfo.usdPrimTypeName}.{attrInfo.apiName}' + ) else: attrApiNames.append(attrInfo.apiName) classInfo.attrs[attrInfo.name] = attrInfo classInfo.attrOrder.append(attrInfo.name) - # Relationship else: relInfo = RelInfo(sdfProp) # Assert unique relationship names if relInfo.name in classInfo.rels: raise Exception( - 'Schema Relationship names must be unique, ' - 'irrespective of namespacing. ' - 'Duplicate name encountered: %s.%s' % - (classInfo.usdPrimTypeName, relInfo.name)) + f'Schema Relationship names must be unique, irrespective of namespacing. Duplicate name encountered: {classInfo.usdPrimTypeName}.{relInfo.name}' + ) elif relInfo.apiName in relApiNames: raise Exception( - 'Schema Relationship API names must be unique. ' - 'Duplicate apiName encountered: %s.%s' % - (classInfo.usdPrimTypeName, relInfo.apiName)) + f'Schema Relationship API names must be unique. Duplicate apiName encountered: {classInfo.usdPrimTypeName}.{relInfo.apiName}' + ) else: relApiNames.append(relInfo.apiName) classInfo.rels[relInfo.name] = relInfo classInfo.relOrder.append(relInfo.name) - + for classInfo in classes: # If this is an applied API schema that does not inherit from # UsdAPISchemaBase directly, ensure that the parent class is also # an applied API Schema. if classInfo.isApi and classInfo.parentCppClassName!='UsdAPISchemaBase': - parentClassInfo = GetClassInfo(classes, classInfo.parentCppClassName) - if parentClassInfo: + if parentClassInfo := GetClassInfo( + classes, classInfo.parentCppClassName + ): if parentClassInfo.isAppliedAPISchema != \ classInfo.isAppliedAPISchema: - raise Exception("API schema '%s' inherits from incompatible " - "base API schema '%s'. Both must be either applied API " - "schemas or non-applied API schemas." % - (classInfo.cppClassName, parentClassInfo.cppClassName)) + raise Exception( + f"API schema '{classInfo.cppClassName}' inherits from incompatible base API schema '{parentClassInfo.cppClassName}'. Both must be either applied API schemas or non-applied API schemas." + ) if parentClassInfo.isMultipleApply != \ classInfo.isMultipleApply: - raise Exception("API schema '%s' inherits from incompatible " - "base API schema '%s'. Both must be either single-apply " - "or multiple-apply." % (classInfo.cppClassName, - parentClassInfo.cppClassName)) + raise Exception( + f"API schema '{classInfo.cppClassName}' inherits from incompatible base API schema '{parentClassInfo.cppClassName}'. Both must be either single-apply or multiple-apply." + ) else: parentClassTfType = Tf.Type.FindByName( classInfo.parentCppClassName) if parentClassTfType and parentClassTfType != Tf.Type.Unknown: if classInfo.isAppliedAPISchema != \ Usd.SchemaRegistry.IsAppliedAPISchema(parentClassTfType): - raise Exception("API schema '%s' inherits from " - "incompatible base API schema '%s'. Both must be " - "either applied API schemas or non-applied API " - " schemas." % (classInfo.cppClassName, - parentClassInfo.cppClassName)) + raise Exception( + f"API schema '{classInfo.cppClassName}' inherits from incompatible base API schema '{parentClassInfo.cppClassName}'. Both must be either applied API schemas or non-applied API schemas." + ) if classInfo.isMultipleApply != \ Usd.SchemaRegistry.IsMultipleApplyAPISchema( parentClassTfType): - raise Exception("API schema '%s' inherits from " - "incompatible base API schema '%s'. Both must be either" - " single-apply or multiple-apply." % - (classInfo.cppClassName, parentClassInfo.cppClassName)) - + raise Exception( + f"API schema '{classInfo.cppClassName}' inherits from incompatible base API schema '{parentClassInfo.cppClassName}'. Both must be either single-apply or multiple-apply." + ) + if hasInvalidFields: raise Exception('Invalid fields specified in schema.') @@ -630,11 +610,27 @@ def _AddToken(tokenDict, tokenId, val, desc): # If token is a reserved word in either language, append with underscore. # 'interface' is not a reserved word but is a macro on Windows when using # COM so we treat it as reserved. - reserved = set(['class', 'default', 'def', 'case', 'switch', 'break', - 'if', 'else', 'struct', 'template', 'interface', - 'float', 'double', 'int', 'char', 'long', 'short']) + reserved = { + 'class', + 'default', + 'def', + 'case', + 'switch', + 'break', + 'if', + 'else', + 'struct', + 'template', + 'interface', + 'float', + 'double', + 'int', + 'char', + 'long', + 'short', + } if tokenId in reserved: - tokenId = tokenId + '_' + tokenId = f'{tokenId}_' if tokenId in tokenDict: token = tokenDict[tokenId] @@ -644,11 +640,10 @@ def _AddToken(tokenDict, tokenId, val, desc): 'Token identifiers must map to exactly one token value. ' 'One-to-Many mapping encountered: %s maps to \"%s\" and \"%s\"' % (token.id, token.value, val)) - + # Update Description - tokenDict[tokenId] = token._replace( - desc=desc + ', ' + token.desc) - + tokenDict[tokenId] = token._replace(desc=f'{desc}, {token.desc}') + else: tokenDict[tokenId] = Token(tokenId, val, desc) @@ -664,33 +659,40 @@ def GatherTokens(classes, libName, libTokens): cls.tokens.add(attr.name) _AddToken(tokenDict, attr.name, attr.rawName, cls.cppClassName) - + # Add default value (if token type) to token set if attr.usdType == 'SdfValueTypeNames->Token' and attr.fallback: fallbackName = _CamelCase(attr.fallback) - desc = 'Default value for %s::Get%sAttr()' % \ - (cls.cppClassName, _ProperCase(attr.name)) + desc = f'Default value for {cls.cppClassName}::Get{_ProperCase(attr.name)}Attr()' cls.tokens.add(fallbackName) _AddToken(tokenDict, fallbackName, attr.fallback, desc) - + # Add Allowed Tokens for this attribute to token set if attr.allowedTokens: for val in attr.allowedTokens: tokenId = _CamelCase(val) - desc = 'Possible value for %s::Get%sAttr()' % \ - (cls.cppClassName, _ProperCase(attr.name)) + desc = f'Possible value for {cls.cppClassName}::Get{_ProperCase(attr.name)}Attr()' cls.tokens.add(tokenId) _AddToken(tokenDict, tokenId, val, desc) - + # Add Relationship Names to token set for rel in cls.rels.values(): cls.tokens.add(rel.name) _AddToken(tokenDict, rel.name, rel.rawName, cls.cppClassName) - + # Add library-wide tokens to token set for token, tokenInfo in libTokens.iteritems(): - _AddToken(tokenDict, token, tokenInfo.get("value", token), _SanitizeDoc(tokenInfo.get("doc", - "Special token for the %s library." % libName), ' ')) + _AddToken( + tokenDict, + token, + tokenInfo.get("value", token), + _SanitizeDoc( + tokenInfo.get( + "doc", f"Special token for the {libName} library." + ), + ' ', + ), + ) return sorted(tokenDict.values(), key=lambda token: token.id.lower()) @@ -857,7 +859,8 @@ def _MakeFlattenedRegistryLayer(filePath): # all the type names. def mangle(typeName): - return '__MANGLED_TO_AVOID_BUILTINS__' + typeName + return f'__MANGLED_TO_AVOID_BUILTINS__{typeName}' + def demangle(typeName): return typeName.replace('__MANGLED_TO_AVOID_BUILTINS__', '') @@ -964,10 +967,9 @@ def InitializeResolver(): resourcePaths = set() pr = Plug.Registry() for t in pr.GetAllDerivedTypes('UsdSchemaBase'): - plugin = pr.GetPluginForType(t) - if plugin: + if plugin := pr.GetPluginForType(t): resourcePaths.add(plugin.resourcePath) - + # The sorting shouldn't matter here, but we do it for consistency # across runs. Ar.DefaultResolver.SetDefaultSearchPath(sorted(list(resourcePaths))) diff --git a/pxr/usd/lib/usdGeom/testenv/testUsdGeomCamera.py b/pxr/usd/lib/usdGeom/testenv/testUsdGeomCamera.py index 48332f7acb5..3bd85401075 100644 --- a/pxr/usd/lib/usdGeom/testenv/testUsdGeomCamera.py +++ b/pxr/usd/lib/usdGeom/testenv/testUsdGeomCamera.py @@ -30,9 +30,7 @@ def _GetSchemaProjection(self, schema, time): val = schema.GetProjectionAttr().Get(time) if val == UsdGeom.Tokens.perspective: return Gf.Camera.Perspective - if val == UsdGeom.Tokens.orthographic: - return Gf.Camera.Orthographic - return None + return Gf.Camera.Orthographic if val == UsdGeom.Tokens.orthographic else None def _GetSchemaClippingRange(self, schema, time): val = schema.GetClippingRangeAttr().Get(time) diff --git a/pxr/usd/lib/usdGeom/testenv/testUsdGeomCollectionAPI.py b/pxr/usd/lib/usdGeom/testenv/testUsdGeomCollectionAPI.py index d995bc91506..a08c8bcbb75 100644 --- a/pxr/usd/lib/usdGeom/testenv/testUsdGeomCollectionAPI.py +++ b/pxr/usd/lib/usdGeom/testenv/testUsdGeomCollectionAPI.py @@ -124,8 +124,9 @@ def test_ValidCases(self): for name in validCollectionNames: collection = UsdGeom.CollectionAPI(root, name) (valid, reason) = collection.Validate() - self.assertTrue(valid, "Collection '%s' was found to be invalid: %s" % - (name, reason)) + self.assertTrue( + valid, f"Collection '{name}' was found to be invalid: {reason}" + ) def test_ErrorCases(self): invalidCollectionNames = ("nonExistentCollection", "faceCountsMismatch", diff --git a/pxr/usd/lib/usdGeom/testenv/testUsdGeomComputeAtTime.py b/pxr/usd/lib/usdGeom/testenv/testUsdGeomComputeAtTime.py index fc930bfab2f..2f119b4cd19 100644 --- a/pxr/usd/lib/usdGeom/testenv/testUsdGeomComputeAtTime.py +++ b/pxr/usd/lib/usdGeom/testenv/testUsdGeomComputeAtTime.py @@ -59,8 +59,7 @@ def assertMatrixListsEqual(self, list1, list2): self.assertTrue(Gf.IsClose(row1, row2, MATRIX_TOLERANCE)) except AssertionError: # Print a more descriptive message. - raise AssertionError( - "Matrices not equal:\n{}\n{}".format(matrix1, matrix2)) + raise AssertionError(f"Matrices not equal:\n{matrix1}\n{matrix2}") def assertAllMatrixListsEqual(self, lists1, lists2): for list1, list2 in zip(lists1, lists2): @@ -77,8 +76,7 @@ def assertExtentsEqual(self, ext1, ext2): Gf.IsClose(ext1[i][d], ext2[i][d], EXTENT_TOLERANCE)) except AssertionError: # Print a more descriptive message. - raise AssertionError( - "Extents not equal:\n{}\n{}".format(ext1, ext2)) + raise AssertionError(f"Extents not equal:\n{ext1}\n{ext2}") def computeInstanceTransforms(self, pi, tr, baseTime, diff --git a/pxr/usd/lib/usdGeom/testenv/testUsdGeomFaceSetAPI.py b/pxr/usd/lib/usdGeom/testenv/testUsdGeomFaceSetAPI.py index e968992bd8b..2f9c4ef7aa1 100644 --- a/pxr/usd/lib/usdGeom/testenv/testUsdGeomFaceSetAPI.py +++ b/pxr/usd/lib/usdGeom/testenv/testUsdGeomFaceSetAPI.py @@ -102,8 +102,9 @@ def test_ValidCases(self): for faceSetName in validFaceSetNames: faceSet = UsdGeom.FaceSetAPI(sphere, faceSetName) (valid, reason) = faceSet.Validate() - self.assertTrue(valid, "FaceSet '%s' was found to be invalid: %s" % - (faceSetName, reason)) + self.assertTrue( + valid, f"FaceSet '{faceSetName}' was found to be invalid: {reason}" + ) def test_ErrorCases(self): invalidFaceSetNames = ("badPartition", "missingIndices", diff --git a/pxr/usd/lib/usdGeom/testenv/testUsdGeomPrimvar.py b/pxr/usd/lib/usdGeom/testenv/testUsdGeomPrimvar.py index 3b4edc8e85a..06df87b007d 100644 --- a/pxr/usd/lib/usdGeom/testenv/testUsdGeomPrimvar.py +++ b/pxr/usd/lib/usdGeom/testenv/testUsdGeomPrimvar.py @@ -44,7 +44,7 @@ def test_PrimvarsAPI(self): self.assertFalse( v1.NameContainsNamespaces() ) _3dpmats = gp_pv.CreatePrimvar('projMats', Sdf.ValueTypeNames.Matrix4dArray, "constant", nPasses) - + # ensure we can create a primvar that contains namespaces! primvarName = 'skel:jointWeights' jointWeights = gp_pv.CreatePrimvar(primvarName, Sdf.ValueTypeNames.FloatArray) @@ -62,7 +62,7 @@ def test_PrimvarsAPI(self): self.assertEqual(len( gp_pv.GetAuthoredPrimvars() ), 4) # displayColor and displayOpacity are builtins, not authored self.assertEqual(len( gp_pv.GetPrimvars() ), 6) - + # Now add some random properties, plus a "manually" created, namespaced # primvar, and reverify p = gp.GetPrim() @@ -93,7 +93,7 @@ def test_PrimvarsAPI(self): self.assertFalse( UsdGeom.Primvar(p.GetAttribute("myColor")) ) self.assertFalse( UsdGeom.Primvar(p.GetAttribute("myBinding")) ) self.assertTrue( UsdGeom.Primvar(p.GetAttribute(v1.GetName())) ) - + # Same classification test through GprimSchema API self.assertTrue( gp_pv.HasPrimvar('u_1') ) self.assertTrue( gp_pv.HasPrimvar('v_1') ) @@ -107,7 +107,7 @@ def test_PrimvarsAPI(self): self.assertEqual( datas[0].GetTypeName(), Sdf.ValueTypeNames.Matrix4dArray ) self.assertEqual( datas[3].GetTypeName(), Sdf.ValueTypeNames.FloatArray ) self.assertEqual( datas[4].GetBaseName(), "v_1" ) - + # Now we'll add some extra configuration and verify that the # interrogative API works properly self.assertEqual( u1.GetInterpolation(), UsdGeom.Tokens.constant ) # fallback @@ -169,7 +169,7 @@ def test_PrimvarsAPI(self): indicesWithInvalid = Vt.IntArray([4, 5, 6, 7, -1, 8]) self.assertTrue(u1.SetIndices(indicesWithInvalid)) self.assertTrue(u1.ComputeFlattened() is None) - + self.assertEqual(u1.GetUnauthoredValuesIndex(), -1) self.assertTrue(u1.SetUnauthoredValuesIndex(2)) self.assertEqual(u1.GetUnauthoredValuesIndex(), 2) @@ -218,7 +218,7 @@ def test_PrimvarsAPI(self): for a, b in zip(u1.ComputeFlattened(1.0), [3.1, 4.1, 2.1]): self.assertTrue(Gf.IsClose(a, b, 1e-5)) - + self.assertNotEqual(u1.ComputeFlattened(1.0), u1.Get(1.0)) self.assertTrue(len(u1.ComputeFlattened(2.0)) == 0) @@ -228,11 +228,11 @@ def test_PrimvarsAPI(self): # (i.e. no default) are recognized as such. Manual name-munging # necessitated by UsdGeomPrimvar's lack of API for accessing # the indices attribute directly! - u1Indices = p.GetAttribute(u1.GetName() + ":indices") + u1Indices = p.GetAttribute(f"{u1.GetName()}:indices") self.assertTrue(u1Indices) u1Indices.ClearDefault() self.assertTrue(u1.IsIndexed()) - + # Finally, ensure the values returned by GetDeclarationInfo # (on new Primvar objects, to test the GprimSchema API) # is identical to the individual queries, and matches what we set above @@ -242,19 +242,19 @@ def test_PrimvarsAPI(self): self.assertEqual(typeName, u1.GetTypeName()) self.assertEqual(interpolation, u1.GetInterpolation()) self.assertEqual(elementSize, u1.GetElementSize()) - + self.assertEqual(name, "u_1") self.assertEqual(typeName, Sdf.ValueTypeNames.FloatArray) self.assertEqual(interpolation, UsdGeom.Tokens.vertex) self.assertEqual(elementSize, 1) - + nv1 = gp_pv.GetPrimvar("v_1") (name, typeName, interpolation, elementSize) = nv1.GetDeclarationInfo() self.assertEqual(name, v1.GetBaseName()) self.assertEqual(typeName, v1.GetTypeName()) self.assertEqual(interpolation, v1.GetInterpolation()) self.assertEqual(elementSize, v1.GetElementSize()) - + self.assertEqual(name, "v_1") self.assertEqual(typeName, Sdf.ValueTypeNames.FloatArray) self.assertEqual(interpolation, UsdGeom.Tokens.faceVarying) @@ -266,7 +266,7 @@ def test_PrimvarsAPI(self): self.assertEqual(typeName, _3dpmats.GetTypeName()) self.assertEqual(interpolation, _3dpmats.GetInterpolation()) self.assertEqual(elementSize, _3dpmats.GetElementSize()) - + self.assertEqual(name, 'projMats') self.assertEqual(typeName, Sdf.ValueTypeNames.Matrix4dArray) self.assertEqual(interpolation, UsdGeom.Tokens.constant) @@ -299,7 +299,7 @@ def test_PrimvarsAPI(self): self.assertEqual(handleid.ComputeFlattened(), v) numPrimvars = len(gp_pv.GetPrimvars()) - + # This check below ensures that the "indices" attributes belonging to # indexed primvars aren't considered to be primvars themselves. self.assertEqual(numPrimvars, 9) diff --git a/pxr/usd/lib/usdGeom/testenv/testUsdGeomSchemata.py b/pxr/usd/lib/usdGeom/testenv/testUsdGeomSchemata.py index d01364cbdbf..341c11320d1 100644 --- a/pxr/usd/lib/usdGeom/testenv/testUsdGeomSchemata.py +++ b/pxr/usd/lib/usdGeom/testenv/testUsdGeomSchemata.py @@ -82,8 +82,10 @@ def test_Basic(self): n = "displayOpacity" name = n[0].upper() + n[1:] - self.assertTrue(("Get" + name + "Attr") in dir(mesh), - ("Get" + name + "Attr() not found in: " + str(dir(mesh)))) + self.assertTrue( + f"Get{name}Attr" in dir(mesh), + f"Get{name}Attr() not found in: {dir(mesh)}", + ) def test_IsA(self): diff --git a/pxr/usd/lib/usdGeom/testenv/testUsdGeomXformable.py b/pxr/usd/lib/usdGeom/testenv/testUsdGeomXformable.py index ac0e02ec43c..3870a8ee6cb 100644 --- a/pxr/usd/lib/usdGeom/testenv/testUsdGeomXformable.py +++ b/pxr/usd/lib/usdGeom/testenv/testUsdGeomXformable.py @@ -427,11 +427,8 @@ def test_InverseOps(self): # We've got tons of xform ops in x now, let's test GetOrderedXformOps API. orderedXformOps = x.GetOrderedXformOps() xformOpOrder = Vt.TokenArray(len(orderedXformOps)) - index = 0 - for op in orderedXformOps: + for index, op in enumerate(orderedXformOps): xformOpOrder[index] = op.GetOpName() - index += 1 - self.assertEqual(xformOpOrder, x.GetXformOpOrderAttr().Get()) def test_AddExistingXformOp(self): diff --git a/pxr/usd/lib/usdRi/testenv/testUsdRiSchemata.py b/pxr/usd/lib/usdRi/testenv/testUsdRiSchemata.py index ae7a18cf0fb..cae8872bbaf 100644 --- a/pxr/usd/lib/usdRi/testenv/testUsdRiSchemata.py +++ b/pxr/usd/lib/usdRi/testenv/testUsdRiSchemata.py @@ -129,7 +129,7 @@ def test_Basic(self): print ("Test RIS Material") risMaterial = UsdRi.MaterialAPI(material.GetPrim()) - assert risMaterial + assert risMaterial assert risMaterial.GetPrim() print ("Test riStatements") @@ -137,7 +137,7 @@ def test_Basic(self): assert riStatements assert riStatements.GetPrim() attr = riStatements.CreateRiAttribute("ModelName", "string").\ - Set('someModelName') + Set('someModelName') assert attr props = riStatements.GetRiAttributes() assert props @@ -147,31 +147,46 @@ def test_Basic(self): prefix = ('primvars:' if Tf.GetEnvSetting('USDRI_STATEMENTS_WRITE_NEW_ATTR_ENCODING') else '') - self.assertEqual(attr.GetName(), - prefix+'ri:attributes:user:ModelName') + self.assertEqual(attr.GetName(), f'{prefix}ri:attributes:user:ModelName') self.assertEqual(attr.Get(), 'someModelName') self.assertEqual(UsdRi.StatementsAPI.GetRiAttributeName(attr), 'ModelName') self.assertEqual(UsdRi.StatementsAPI.GetRiAttributeNameSpace(attr), 'user') assert UsdRi.StatementsAPI.IsRiAttribute(attr) - self.assertEqual(UsdRi.StatementsAPI.MakeRiAttributePropertyName('myattr'), - prefix+'ri:attributes:user:myattr') - self.assertEqual(UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice:myattr'), - prefix+'ri:attributes:dice:myattr') - self.assertEqual(UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice.myattr'), - prefix+'ri:attributes:dice:myattr') - self.assertEqual(UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice_myattr'), - prefix+'ri:attributes:dice:myattr') + self.assertEqual( + UsdRi.StatementsAPI.MakeRiAttributePropertyName('myattr'), + f'{prefix}ri:attributes:user:myattr', + ) + self.assertEqual( + UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice:myattr'), + f'{prefix}ri:attributes:dice:myattr', + ) + self.assertEqual( + UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice.myattr'), + f'{prefix}ri:attributes:dice:myattr', + ) + self.assertEqual( + UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice_myattr'), + f'{prefix}ri:attributes:dice:myattr', + ) # period is stronger separator than underscore, when both are present - self.assertEqual(UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice_my.attr'), - prefix+'ri:attributes:dice_my:attr') + self.assertEqual( + UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice_my.attr'), + f'{prefix}ri:attributes:dice_my:attr', + ) # multiple tokens concatted with underscores - self.assertEqual(UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice:my1:long:attr'), - prefix+'ri:attributes:dice:my1_long_attr') - self.assertEqual(UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice.my2.long.attr'), - prefix+'ri:attributes:dice:my2_long_attr') - self.assertEqual(UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice_my3_long_attr'), - prefix+'ri:attributes:dice:my3_long_attr') + self.assertEqual( + UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice:my1:long:attr'), + f'{prefix}ri:attributes:dice:my1_long_attr', + ) + self.assertEqual( + UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice.my2.long.attr'), + f'{prefix}ri:attributes:dice:my2_long_attr', + ) + self.assertEqual( + UsdRi.StatementsAPI.MakeRiAttributePropertyName('dice_my3_long_attr'), + f'{prefix}ri:attributes:dice:my3_long_attr', + ) self.assertEqual(riStatements.GetCoordinateSystem(), '') self.assertEqual(UsdRi.StatementsAPI(model).GetModelCoordinateSystems(), []) diff --git a/pxr/usd/lib/usdShade/testenv/testUsdShadeInterfaceInputConsumers.py b/pxr/usd/lib/usdShade/testenv/testUsdShadeInterfaceInputConsumers.py index eae9de43906..a1a83f3398b 100644 --- a/pxr/usd/lib/usdShade/testenv/testUsdShadeInterfaceInputConsumers.py +++ b/pxr/usd/lib/usdShade/testenv/testUsdShadeInterfaceInputConsumers.py @@ -145,34 +145,58 @@ def test_InterfaceConsumers(self): for interfaceInput, consumers in interfaceConsumersMapping.iteritems(): if interfaceInput.GetAttr().GetBaseName() == "floatInput": - self.assertEqual(set([i.GetAttr().GetBaseName() for i in consumers]), - set(["nodeGraph1FloatInput", "nodeGraph2FloatInput", - "shader1Input1", "shader2Input2"])) + self.assertEqual( + {i.GetAttr().GetBaseName() for i in consumers}, + { + "nodeGraph1FloatInput", + "nodeGraph2FloatInput", + "shader1Input1", + "shader2Input2", + }, + ) elif interfaceInput.GetAttr().GetBaseName() == "colorInput": - self.assertEqual(set([i.GetAttr().GetBaseName() for i in consumers]), - set(["nodeGraph1ColorInput", "nodeGraph2ColorInput", - "shader2Input1", "shader1Input2"])) + self.assertEqual( + {i.GetAttr().GetBaseName() for i in consumers}, + { + "nodeGraph1ColorInput", + "nodeGraph2ColorInput", + "shader2Input1", + "shader1Input2", + }, + ) else: - Tf.RaiseRuntimeError("Unexpected input: %s" % - interfaceInput.GetFullName()) + Tf.RaiseRuntimeError(f"Unexpected input: {interfaceInput.GetFullName()}") transitiveInterfaceMapping = material.ComputeInterfaceInputConsumersMap(True) self.assertEqual(len(transitiveInterfaceMapping), 2) for interfaceInput, consumers in transitiveInterfaceMapping.iteritems(): if interfaceInput.GetAttr().GetBaseName() == "floatInput": - self.assertEqual(set([i.GetAttr().GetBaseName() for i in consumers]), - set(["nestedShader1Input2", "nestedShader2Input1", - "shader1Input1", "shader2Input2", - "nestedShader3Input2", "nestedNodeGraphInput1"])) + self.assertEqual( + {i.GetAttr().GetBaseName() for i in consumers}, + { + "nestedShader1Input2", + "nestedShader2Input1", + "shader1Input1", + "shader2Input2", + "nestedShader3Input2", + "nestedNodeGraphInput1", + }, + ) elif interfaceInput.GetAttr().GetBaseName() == "colorInput": - self.assertEqual(set([i.GetAttr().GetBaseName() for i in consumers]), - set(["nestedShader1Input1", "nestedShader2Input2", - "shader1Input2", "shader2Input1", - "nestedShader3Input1", "nestedNodeGraphInput2"])) + self.assertEqual( + {i.GetAttr().GetBaseName() for i in consumers}, + { + "nestedShader1Input1", + "nestedShader2Input2", + "shader1Input2", + "shader2Input1", + "nestedShader3Input1", + "nestedNodeGraphInput2", + }, + ) else: - Tf.RaiseRuntimeError("Unexpected input: %s" % - interfaceInput.GetFullName()) + Tf.RaiseRuntimeError(f"Unexpected input: {interfaceInput.GetFullName()}") if __name__ == '__main__': unittest.main() diff --git a/pxr/usd/lib/usdShade/testenv/testUsdShadeMaterialAuthoring.py b/pxr/usd/lib/usdShade/testenv/testUsdShadeMaterialAuthoring.py index 755c853831d..8999a4e79a0 100644 --- a/pxr/usd/lib/usdShade/testenv/testUsdShadeMaterialAuthoring.py +++ b/pxr/usd/lib/usdShade/testenv/testUsdShadeMaterialAuthoring.py @@ -59,16 +59,11 @@ def MakePatternPath(base, variant, prop = None): return retval def MakeMaterialPath(base, prop = None): - retval = materialsPath.AppendChild(base + "Material") + retval = materialsPath.AppendChild(f"{base}Material") if prop: retval = retval.AppendProperty(prop) return retval - #def CreateTerminal(material, name, targetPath): - #terminalRel = material.GetPrim().CreateRelationship("terminal:%s" % name) - #terminalRel.SetTargets([targetPath,]); - #return terminalRel - def SetupShading(stage): # First create the shading prims UsdGeom.Scope.Define(stage, shadersPath) @@ -175,8 +170,8 @@ def ValidateMaterial(stage): # This is the root prim that a client would target to pull in shading refs = rootPrim.GetReferences() # XXX We need a better way of specifying self-references - refs.AddReference("./"+fileName, "/MaterialBindingVariants") - refs.AddReference("./"+fileName, "/ShadingDefs") + refs.AddReference(f"./{fileName}", "/MaterialBindingVariants") + refs.AddReference(f"./{fileName}", "/ShadingDefs") stage.GetRootLayer().Save() @@ -197,7 +192,7 @@ def ValidateMaterial(stage): SetupShading(stage) # Reference the shading directly refs = rootPrim.GetReferences() - refs.AddReference("./"+fileName, "/ShadingDefs") + refs.AddReference(f"./{fileName}", "/ShadingDefs") # Now pick up the newly composed material prims allMaterials = [ stage.GetPrimAtPath("/ModelShading/Materials/HairMaterial"), diff --git a/pxr/usd/lib/usdShade/testenv/testUsdShadeMaterialBaseMaterial.py b/pxr/usd/lib/usdShade/testenv/testUsdShadeMaterialBaseMaterial.py index f2c8cda1076..944bd2ac547 100644 --- a/pxr/usd/lib/usdShade/testenv/testUsdShadeMaterialBaseMaterial.py +++ b/pxr/usd/lib/usdShade/testenv/testUsdShadeMaterialBaseMaterial.py @@ -33,8 +33,7 @@ def _SetupShading(self, stage): # we want it to appear at the top rootPrim = stage.DefinePrim("/ModelShading") - materialsPath = rootPrim.GetPath().AppendChild('Materials') - return materialsPath + return rootPrim.GetPath().AppendChild('Materials') def _TestShading(self, stage, materialsPath): diff --git a/pxr/usd/lib/usdShade/testenv/testUsdShadeMaterialSpecializesBaseComposition.py b/pxr/usd/lib/usdShade/testenv/testUsdShadeMaterialSpecializesBaseComposition.py index 6f328875385..15ed6b5540b 100644 --- a/pxr/usd/lib/usdShade/testenv/testUsdShadeMaterialSpecializesBaseComposition.py +++ b/pxr/usd/lib/usdShade/testenv/testUsdShadeMaterialSpecializesBaseComposition.py @@ -65,8 +65,8 @@ def test_ParentIsAcrossReferenceArc(self): self.assertTrue(stage) looksScope = '/Shot/Set/SetChild/ReferencedAsset/Looks/' - child = self._GetMaterial(stage, looksScope + 'ChildMaterial') - base = self._GetMaterial(stage, looksScope + 'BaseMaterial') + child = self._GetMaterial(stage, f'{looksScope}ChildMaterial') + base = self._GetMaterial(stage, f'{looksScope}BaseMaterial') self.assertFalse(base.GetBaseMaterial()) self.assertEqual(child.GetBaseMaterial().GetPath(), base.GetPath()) @@ -78,8 +78,8 @@ def test_MultipleReferencedParents(self): self.assertTrue(stage) basePath = '/Shot/Set/SetChild/ReferencedAsset/Looks/' - child = self._GetMaterial(stage, basePath + 'ChildMaterial') - base = self._GetMaterial(stage, basePath + 'BaseMaterial') + child = self._GetMaterial(stage, f'{basePath}ChildMaterial') + base = self._GetMaterial(stage, f'{basePath}BaseMaterial') self.assertFalse(base.GetBaseMaterial()) self.assertEqual(child.GetBaseMaterial().GetPath(), base.GetPath()) diff --git a/pxr/usd/lib/usdShade/testenv/testUsdShadeNodeGraphs.py b/pxr/usd/lib/usdShade/testenv/testUsdShadeNodeGraphs.py index 4570bdbf5ab..773d900c78a 100644 --- a/pxr/usd/lib/usdShade/testenv/testUsdShadeNodeGraphs.py +++ b/pxr/usd/lib/usdShade/testenv/testUsdShadeNodeGraphs.py @@ -39,45 +39,45 @@ class TestUsdShadeNodeGraphs(unittest.TestCase): def _SetupStage(self): usdStage = Usd.Stage.CreateInMemory() self.assertTrue(usdStage) - + nodeGraph = UsdShade.NodeGraph.Define(usdStage, NODEGRAPH_PATH) self.assertTrue(nodeGraph) - + for i in range(len(SHADERS)): outputName = OUTPUTS[i] shaderName = SHADERS[i] - + paramName = PARAMS[i] inputName = INPUTS[i] - - shaderPath = '%s/%s' % (NODEGRAPH_PATH, shaderName) + + shaderPath = f'{NODEGRAPH_PATH}/{shaderName}' shader = UsdShade.Shader.Define(usdStage, shaderPath) self.assertTrue(shader) - + shaderInput = shader.CreateInput(paramName, Sdf.ValueTypeNames.Float) self.assertTrue(shaderInput) - + nodeGraphInput = nodeGraph.CreateInput(inputName, Sdf.ValueTypeNames.Float) self.assertTrue(nodeGraphInput) - + shaderOutput = shader.CreateOutput(outputName, Sdf.ValueTypeNames.Int) self.assertTrue(shaderOutput) - + nodeGraphOutput = nodeGraph.CreateOutput(outputName, Sdf.ValueTypeNames.Int) self.assertTrue(nodeGraphOutput) - + self.assertTrue(nodeGraphOutput.ConnectToSource(shaderOutput)) - + self.assertTrue(shaderInput.ConnectToSource(nodeGraphInput)) nestedNodeGraph = UsdShade.NodeGraph.Define(usdStage, NESTED_NODEGRAPH_PATH) self.assertTrue(nestedNodeGraph) - + nestedNodeGraphShader = UsdShade.Shader.Define(usdStage, NESTED_NODEGRAPH_SHADER_PATH) self.assertTrue(nestedNodeGraphShader) @@ -88,11 +88,11 @@ def _SetupStage(self): nestedNodeGraphInput.ConnectToSource( NODEGRAPH_PATH.AppendProperty("inputs:InputTwo")) - + nestedNodeGraphOutput = nestedNodeGraph.CreateOutput("NestedOutput", Sdf.ValueTypeNames.Int) self.assertTrue(nestedNodeGraphOutput) - + nestedNodeGraphShaderOutput = nestedNodeGraphShader.CreateOutput("NestedShaderOutput", Sdf.ValueTypeNames.Int) self.assertTrue(nestedNodeGraphShaderOutput) diff --git a/pxr/usd/lib/usdSkel/examples.py b/pxr/usd/lib/usdSkel/examples.py index b9539804a2c..aebcc4592e2 100644 --- a/pxr/usd/lib/usdSkel/examples.py +++ b/pxr/usd/lib/usdSkel/examples.py @@ -37,8 +37,7 @@ def PopulateAllSkelRoots(stage, cache): #! [IterSkels] def IterSkels(skelRootPrim, skelCache): for descendant in Usd.PrimRange(skelRootPrim): - query = skelCache.GetSkelQuery(descendant) - if query: + if query := skelCache.GetSkelQuery(descendant): yield (descendant,query) #! [IterSkels] diff --git a/pxr/usd/lib/usdUI/testenv/testUsdUIBackdrop.py b/pxr/usd/lib/usdUI/testenv/testUsdUIBackdrop.py index d7cc3d6ad25..8277100d8cf 100644 --- a/pxr/usd/lib/usdUI/testenv/testUsdUIBackdrop.py +++ b/pxr/usd/lib/usdUI/testenv/testUsdUIBackdrop.py @@ -34,7 +34,7 @@ def test_Basic(self): rootPrim = stage.DefinePrim("/ModelShading") materialsPath = rootPrim.GetPath().AppendChild('Materials') parentMaterialPath = materialsPath.AppendChild('ParentMaterial') - + # Test Backdrop backdrop = UsdUI.Backdrop.Define( stage, parentMaterialPath.AppendChild("Backdrop_1")) @@ -44,8 +44,9 @@ def test_Basic(self): # Test Description descAttr = backdrop.GetDescriptionAttr() assert descAttr - assert descAttr.GetTypeName() == 'token', \ - "Type of description attribute should be 'token', not %s" % descAttr.GetTypeName() + assert ( + descAttr.GetTypeName() == 'token' + ), f"Type of description attribute should be 'token', not {descAttr.GetTypeName()}" descAttr.Set("Backdrop test description") stage.GetRootLayer().Save() diff --git a/pxr/usd/lib/usdUI/testenv/testUsdUINodeGraphNode.py b/pxr/usd/lib/usdUI/testenv/testUsdUINodeGraphNode.py index 7dae2f84d11..9dca10eb267 100644 --- a/pxr/usd/lib/usdUI/testenv/testUsdUINodeGraphNode.py +++ b/pxr/usd/lib/usdUI/testenv/testUsdUINodeGraphNode.py @@ -28,56 +28,58 @@ class TestUsdUINodeGraphNode(unittest.TestCase): def test_Basic(self): - fileName = "nodeGraph.usda" - stage = Usd.Stage.CreateNew(fileName) - - # Create this prim first, since it's the "entrypoint" to the layer, and - # we want it to appear at the top - rootPrim = stage.DefinePrim("/ANode") - - # Test Node - nodeGraphNode = UsdUI.NodeGraphNodeAPI.Apply(rootPrim) - assert(nodeGraphNode) - - # Test Position - posAttr = nodeGraphNode.GetPosAttr() - assert not posAttr - posAttr = nodeGraphNode.CreatePosAttr() - assert posAttr, "Failed creating pos attribute" - assert posAttr.GetTypeName() == 'float2', \ - "Type of position attribute should be 'float2', not %s" % posAttr.GetTypeName() - posAttr.Set(Gf.Vec2f(3, 2)) - - # Test Stacking Order - stackingOrderAttr = nodeGraphNode.GetStackingOrderAttr() - assert not stackingOrderAttr - stackingOrderAttr = nodeGraphNode.CreateStackingOrderAttr() - assert stackingOrderAttr, "Failed creating stacking order attribute" - assert stackingOrderAttr.GetTypeName() == 'int', \ - "Type of position attribute should be 'int', not %s" % \ - stackingOrderAttr.GetTypeName() - stackingOrderAttr.Set(100) - - # Test Display Color - displayColorAttr = nodeGraphNode.GetDisplayColorAttr() - assert not displayColorAttr - displayColorAttr = nodeGraphNode.CreateDisplayColorAttr() - assert displayColorAttr, "Failed creating display color attribute" - assert displayColorAttr.GetTypeName() == 'color3f', \ - "Type of position attribute should be 'color3f', not %s" % \ - displayColorAttr.GetTypeName() - displayColorAttr.Set(Gf.Vec3f(1, 0, 0)) + fileName = "nodeGraph.usda" + stage = Usd.Stage.CreateNew(fileName) - # Test Size - sizeAttr = nodeGraphNode.GetSizeAttr() - assert not sizeAttr - sizeAttr = nodeGraphNode.CreateSizeAttr() - assert sizeAttr, "Failed creating size attribute" - assert sizeAttr.GetTypeName() == 'float2', \ - "Type of size attribute should be 'float2', not %s" % sizeAttr.GetTypeName() - sizeAttr.Set(Gf.Vec2f(300, 400)) - - stage.GetRootLayer().Save() + # Create this prim first, since it's the "entrypoint" to the layer, and + # we want it to appear at the top + rootPrim = stage.DefinePrim("/ANode") + + # Test Node + nodeGraphNode = UsdUI.NodeGraphNodeAPI.Apply(rootPrim) + assert(nodeGraphNode) + + # Test Position + posAttr = nodeGraphNode.GetPosAttr() + assert not posAttr + posAttr = nodeGraphNode.CreatePosAttr() + assert posAttr, "Failed creating pos attribute" + assert ( + posAttr.GetTypeName() == 'float2' + ), f"Type of position attribute should be 'float2', not {posAttr.GetTypeName()}" + posAttr.Set(Gf.Vec2f(3, 2)) + + # Test Stacking Order + stackingOrderAttr = nodeGraphNode.GetStackingOrderAttr() + assert not stackingOrderAttr + stackingOrderAttr = nodeGraphNode.CreateStackingOrderAttr() + assert stackingOrderAttr, "Failed creating stacking order attribute" + assert ( + stackingOrderAttr.GetTypeName() == 'int' + ), f"Type of position attribute should be 'int', not {stackingOrderAttr.GetTypeName()}" + stackingOrderAttr.Set(100) + + # Test Display Color + displayColorAttr = nodeGraphNode.GetDisplayColorAttr() + assert not displayColorAttr + displayColorAttr = nodeGraphNode.CreateDisplayColorAttr() + assert displayColorAttr, "Failed creating display color attribute" + assert ( + displayColorAttr.GetTypeName() == 'color3f' + ), f"Type of position attribute should be 'color3f', not {displayColorAttr.GetTypeName()}" + displayColorAttr.Set(Gf.Vec3f(1, 0, 0)) + + # Test Size + sizeAttr = nodeGraphNode.GetSizeAttr() + assert not sizeAttr + sizeAttr = nodeGraphNode.CreateSizeAttr() + assert sizeAttr, "Failed creating size attribute" + assert ( + sizeAttr.GetTypeName() == 'float2' + ), f"Type of size attribute should be 'float2', not {sizeAttr.GetTypeName()}" + sizeAttr.Set(Gf.Vec2f(300, 400)) + + stage.GetRootLayer().Save() if __name__ == "__main__": unittest.main() diff --git a/pxr/usd/lib/usdUI/testenv/testUsdUISceneGraphPrim.py b/pxr/usd/lib/usdUI/testenv/testUsdUISceneGraphPrim.py index ae8f1d16a00..a3b513a75a6 100644 --- a/pxr/usd/lib/usdUI/testenv/testUsdUISceneGraphPrim.py +++ b/pxr/usd/lib/usdUI/testenv/testUsdUISceneGraphPrim.py @@ -30,35 +30,35 @@ class TestUsdUISceneGraphPrim(unittest.TestCase): def test_Basic(self): fileName = "sceneGraph.usda" stage = Usd.Stage.CreateNew(fileName) - + # Create this prim first, since it's the "entrypoint" to the layer, and # we want it to appear at the top rootPrim = stage.DefinePrim("/ANode") - + # Test Node sceneGraphPrim = UsdUI.SceneGraphPrimAPI.Apply(rootPrim) assert(sceneGraphPrim) - + # Test displayName displayNameAttr = sceneGraphPrim.GetDisplayNameAttr() assert not displayNameAttr displayNameAttr = sceneGraphPrim.CreateDisplayNameAttr() assert displayNameAttr, "Failed creating display attribute" - assert displayNameAttr.GetTypeName() == 'token', \ - "Type of position attribute should be 'token', not %s" % \ - displayNameAttr.GetTypeName() + assert ( + displayNameAttr.GetTypeName() == 'token' + ), f"Type of position attribute should be 'token', not {displayNameAttr.GetTypeName()}" displayNameAttr.Set('foo') - + # Test Display Color displayGroupAttr = sceneGraphPrim.GetDisplayGroupAttr() assert not displayGroupAttr displayGroupAttr = sceneGraphPrim.CreateDisplayGroupAttr() assert displayGroupAttr, "Failed creating display color attribute" - assert displayGroupAttr.GetTypeName() == 'token', \ - "Type of position attribute should be 'token', not %s" % \ - displayGroupAttr.GetTypeName() + assert ( + displayGroupAttr.GetTypeName() == 'token' + ), f"Type of position attribute should be 'token', not {displayGroupAttr.GetTypeName()}" displayGroupAttr.Set("bar") - + stage.GetRootLayer().Save() if __name__ == "__main__": diff --git a/pxr/usd/lib/usdUtils/testenv/testUsdUtilsCoalescingDiagnosticDelegate.py b/pxr/usd/lib/usdUtils/testenv/testUsdUtilsCoalescingDiagnosticDelegate.py index 0e722bb4a60..f7bacc72adc 100644 --- a/pxr/usd/lib/usdUtils/testenv/testUsdUtilsCoalescingDiagnosticDelegate.py +++ b/pxr/usd/lib/usdUtils/testenv/testUsdUtilsCoalescingDiagnosticDelegate.py @@ -29,35 +29,35 @@ def _genWarning(): Tf.Warn('.') -EXPECTED_LINE_NO = 30 +EXPECTED_LINE_NO = 30 EXPECTED_FUNC_NAME = '__main__._genWarning' delegate = UsdUtils.CoalescingDiagnosticDelegate() # Test dumping of diagnostics (this will be compared in baseline/output.txt) -for i in range(0,10): +for _ in range(0,10): _genWarning() delegate.DumpCoalescedDiagnosticsToStdout() # Test collection of unfiltered diagnostics -for i in range(0,3): +for _ in range(0,3): _genWarning() unfiltered = delegate.TakeUncoalescedDiagnostics() assert len(unfiltered) == 3 -for i in range(0,3): - assert unfiltered[0].sourceLineNumber == EXPECTED_LINE_NO +for _ in range(0,3): + assert unfiltered[0].sourceLineNumber == EXPECTED_LINE_NO assert unfiltered[0].sourceFunction == EXPECTED_FUNC_NAME # Test collection of filtered diagnostics -for i in range(0,8): +for _ in range(0,8): _genWarning() filtered = delegate.TakeCoalescedDiagnostics() assert len(filtered) == 1 filteredDiagnostic = filtered[0] -assert filteredDiagnostic.sharedItem.sourceLineNumber == EXPECTED_LINE_NO +assert filteredDiagnostic.sharedItem.sourceLineNumber == EXPECTED_LINE_NO assert filteredDiagnostic.sharedItem.sourceFunction == EXPECTED_FUNC_NAME import pprint diff --git a/pxr/usd/lib/usdUtils/testenv/testUsdUtilsStitch.py b/pxr/usd/lib/usdUtils/testenv/testUsdUtilsStitch.py index ff0d7e2cc45..f8adb9e2b10 100644 --- a/pxr/usd/lib/usdUtils/testenv/testUsdUtilsStitch.py +++ b/pxr/usd/lib/usdUtils/testenv/testUsdUtilsStitch.py @@ -56,14 +56,20 @@ def test_AllPrimsFullyCopied(self): for prims in [self.rootprims_a, self.rootprims_b]: for rootprim in prims: for child in rootprim.nameChildren: - self.assertTrue(self.layers[0].GetPrimAtPath(child.path), - 'Missing object at ' + str(child.path)) + self.assertTrue( + self.layers[0].GetPrimAtPath(child.path), + f'Missing object at {str(child.path)}', + ) for attr in rootprim.attributes: - self.assertTrue(self.layers[0].GetAttributeAtPath(attr.path), - 'Missing attribute at ' + str(attr.path)) + self.assertTrue( + self.layers[0].GetAttributeAtPath(attr.path), + f'Missing attribute at {str(attr.path)}', + ) for rel in rootprim.relationships: - self.assertTrue(self.layers[0].GetRelationshipAtPath(rel.path), - 'Missing relationship at ' + str(rel.path)) + self.assertTrue( + self.layers[0].GetRelationshipAtPath(rel.path), + f'Missing relationship at {str(rel.path)}', + ) def test_AllTimeSamplesMerged(self): timesamples_a = self.layers[1].ListAllTimeSamples() diff --git a/pxr/usd/lib/usdUtils/testenv/testUsdUtilsStitchClips.py b/pxr/usd/lib/usdUtils/testenv/testUsdUtilsStitchClips.py index 540a793a3ab..6f3524e38d1 100644 --- a/pxr/usd/lib/usdUtils/testenv/testUsdUtilsStitchClips.py +++ b/pxr/usd/lib/usdUtils/testenv/testUsdUtilsStitchClips.py @@ -67,21 +67,25 @@ def setUp(self): self.endTimeCode = 108 rootLayer = Sdf.Layer.FindOrOpen(self.baseName) self.rootLayer = rootLayer if rootLayer else Sdf.Layer.CreateNew(self.baseName) - UsdUtils.StitchClips(self.rootLayer, self.layerFileNames[0:7], - self.clipPath, self.startTimeCode, self.endTimeCode) + UsdUtils.StitchClips( + self.rootLayer, + self.layerFileNames[:7], + self.clipPath, + self.startTimeCode, + self.endTimeCode, + ) self.setupComplete = True def test_ValidClipMetadata(self): clipPrim = self.rootLayer.GetPrimAtPath(self.clipPath) self.assertTrue(clipPrim) - self.assertEqual(set(clipPrim.ListInfoKeys()), - set(['clips', 'specifier'])) - self.assertEqual(set(clipPrim.GetInfo('clips').keys()), - set(['default'])) - self.assertEqual(set(clipPrim.GetInfo('clips')['default'].keys()), - set(['times', 'assetPaths', 'primPath', - 'manifestAssetPath', 'active'])) + self.assertEqual(set(clipPrim.ListInfoKeys()), {'clips', 'specifier'}) + self.assertEqual(set(clipPrim.GetInfo('clips').keys()), {'default'}) + self.assertEqual( + set(clipPrim.GetInfo('clips')['default'].keys()), + {'times', 'assetPaths', 'primPath', 'manifestAssetPath', 'active'}, + ) def test_ValidUsdLayerGeneration(self): self.assertTrue(self.rootLayer) @@ -104,7 +108,7 @@ def test_RelativeAssetPaths(self): # ensure all paths are relative import itertools - self.assertTrue(not any([os.path.isabs(i.path) for i in assetPaths])) + self.assertTrue(not any(os.path.isabs(i.path) for i in assetPaths)) # This test ensures that we are grabbing our frame data from # the layers directly so we incur no precision loss from string diff --git a/pxr/usd/plugin/usdAbc/testenv/testUsdAbcCamera.py b/pxr/usd/plugin/usdAbc/testenv/testUsdAbcCamera.py index 14c9eea413c..fd95a1df3d4 100644 --- a/pxr/usd/plugin/usdAbc/testenv/testUsdAbcCamera.py +++ b/pxr/usd/plugin/usdAbc/testenv/testUsdAbcCamera.py @@ -35,9 +35,9 @@ def _RoundTripFileNames(self, baseName): Filenames for testing a round trip usd->abc->usd. First file name uses FindDataFile to locate it within a test. """ - oldUsdFile = baseName + '.usd' - abcFile = baseName + '_1.abc' - newUsdFile = baseName + '_2.usd' + oldUsdFile = f'{baseName}.usd' + abcFile = f'{baseName}_1.abc' + newUsdFile = f'{baseName}_2.usd' return oldUsdFile, abcFile, newUsdFile diff --git a/pxr/usd/plugin/usdAbc/testenv/testUsdAbcInstancing.py b/pxr/usd/plugin/usdAbc/testenv/testUsdAbcInstancing.py index f615a84ab35..b35d66819e2 100644 --- a/pxr/usd/plugin/usdAbc/testenv/testUsdAbcInstancing.py +++ b/pxr/usd/plugin/usdAbc/testenv/testUsdAbcInstancing.py @@ -28,9 +28,9 @@ class TestUsdAbcInstancing(unittest.TestCase): def test_InstanceConversion(self): name = "nestedInstancing" - layer = Sdf.Layer.FindOrOpen('%s.abc' % (name, )) + layer = Sdf.Layer.FindOrOpen(f'{name}.abc') self.assertTrue(layer) - layer.Export('%s.%s.usda' % (name, os.environ['USD_ABC_TESTSUFFIX'])) + layer.Export(f"{name}.{os.environ['USD_ABC_TESTSUFFIX']}.usda") if __name__ == "__main__": unittest.main() diff --git a/pxr/usdImaging/bin/testusdview/testenv/testUsdviewNavigationKeys/testUsdviewNavigationKeys.py b/pxr/usdImaging/bin/testusdview/testenv/testUsdviewNavigationKeys/testUsdviewNavigationKeys.py index 792eb139960..2b2f79b8861 100644 --- a/pxr/usdImaging/bin/testusdview/testenv/testUsdviewNavigationKeys/testUsdviewNavigationKeys.py +++ b/pxr/usdImaging/bin/testusdview/testenv/testUsdviewNavigationKeys/testUsdviewNavigationKeys.py @@ -77,21 +77,21 @@ def _testBasic(appController): # chain, so it takes two "move right" actions to select each level of # path hierarchy path = Sdf.Path("/World/sets/setModel") - for i in xrange(2 * path.pathElementCount): + for _ in xrange(2 * path.pathElementCount): _postAndProcessKeyEvent(QtCore.Qt.Key_Right, appObj) assert len(selectionDataModel.getPrims()) == 1 assert selectionDataModel.getFocusPrim().GetPrimPath() == path # Now roll it all back up - for i in xrange(1, 2 * path.pathElementCount): + for _ in xrange(1, 2 * path.pathElementCount): # Send the event to mainWindow to ensure our app filter reroutes it # to the focusWidget. _postAndProcessKeyEvent(QtCore.Qt.Key_Left, appObj) assert len(selectionDataModel.getPrims()) == 1 assert selectionDataModel.getFocusPrim().IsPseudoRoot() - + # Then test that right/left keys sent to other widgets (including the # MainWindow) will result in transport movement startFrame = stage.GetStartTimeCode() @@ -113,7 +113,7 @@ def _testBasic(appController): escSender = EscapeSender(appController._ui.menuView) QtCore.QTimer.singleShot(500, escSender, QtCore.SLOT("doIt()")) _popupViewMenu(appController) - + # Modal dialogs won't receive events sent to the application object, # so we must send it to the widget itself. Which means we can't use any # of usdview's modals, since we only use static Qt methods that don't diff --git a/pxr/usdImaging/bin/testusdview/testenv/testUsdviewNoPlugins/testUsdviewNoPlugins.py b/pxr/usdImaging/bin/testusdview/testenv/testUsdviewNoPlugins/testUsdviewNoPlugins.py index 0ce8b5115cb..c222b640c59 100644 --- a/pxr/usdImaging/bin/testusdview/testenv/testUsdviewNoPlugins/testUsdviewNoPlugins.py +++ b/pxr/usdImaging/bin/testusdview/testenv/testUsdviewNoPlugins/testUsdviewNoPlugins.py @@ -30,7 +30,7 @@ def _testBasic(appController): expectedItems = [u'&File', u'Edit Prim(s)', u'&Options', u'&View', u'Window', u'Debug'] actualItems = [p.text() for p in menuItems] - failureStr = str(expectedItems) + ' != ' + str(actualItems) + failureStr = f'{expectedItems} != {actualItems}' assert actualItems == expectedItems, failureStr def testUsdviewInputFunction(appController): diff --git a/pxr/usdImaging/bin/testusdview/testenv/testUsdviewPrimPathBar/testUsdviewPrimPathBar.py b/pxr/usdImaging/bin/testusdview/testenv/testUsdviewPrimPathBar/testUsdviewPrimPathBar.py index 2d8b6d1e31f..ce0e81d17bf 100644 --- a/pxr/usdImaging/bin/testusdview/testenv/testUsdviewPrimPathBar/testUsdviewPrimPathBar.py +++ b/pxr/usdImaging/bin/testusdview/testenv/testUsdviewPrimPathBar/testUsdviewPrimPathBar.py @@ -50,7 +50,7 @@ def _assertPathIsPrim(appController): assert Sdf.Path(p).IsAbsoluteRootOrPrimPath() def _assertPathIsProp(appController): - for p in _getPath(appController).split(','): + for _ in _getPath(appController).split(','): assert Sdf.Path(_getPath(appController)).IsPropertyPath() def _assertSelectedPrims(appController, primNames): diff --git a/pxr/usdImaging/bin/testusdview/testenv/testUsdviewPropertySearch/testUsdviewPropertySearch.py b/pxr/usdImaging/bin/testusdview/testenv/testUsdviewPropertySearch/testUsdviewPropertySearch.py index 241d0345128..0a72b002937 100644 --- a/pxr/usdImaging/bin/testusdview/testenv/testUsdviewPropertySearch/testUsdviewPropertySearch.py +++ b/pxr/usdImaging/bin/testusdview/testenv/testUsdviewPropertySearch/testUsdviewPropertySearch.py @@ -33,8 +33,8 @@ def _assertSelectedProp(appController, propName): else: assert len(selectedComputed) == 1 selectedPropName = selectedComputed[0].GetName() - - assert propName == selectedPropName, propName + '!=' + selectedPropName + + assert propName == selectedPropName, f'{propName}!={selectedPropName}' def _selectPrim(appController, primName): appController._ui.primViewLineEdit.setText(primName) diff --git a/pxr/usdImaging/bin/usdview/usdview.py b/pxr/usdImaging/bin/usdview/usdview.py index cd57ec53748..38fb67fb6b6 100644 --- a/pxr/usdImaging/bin/usdview/usdview.py +++ b/pxr/usdImaging/bin/usdview/usdview.py @@ -31,5 +31,5 @@ try: Usdviewq.Launcher().Run() except Usdviewq.InvalidUsdviewOption as e: - print("ERROR: " + e.message, file=sys.stderr) + print(f"ERROR: {e.message}", file=sys.stderr) sys.exit(1) diff --git a/pxr/usdImaging/lib/usdviewq/__init__.py b/pxr/usdImaging/lib/usdviewq/__init__.py index ae2e529e478..fb3a0a37d6a 100644 --- a/pxr/usdImaging/lib/usdviewq/__init__.py +++ b/pxr/usdImaging/lib/usdviewq/__init__.py @@ -220,7 +220,7 @@ def LaunchPreamble(self, arg_parse_result): AppController.clearSettings() # Find the resource directory - resourceDir = os.path.dirname(os.path.realpath(__file__)) + "/" + resourceDir = f"{os.path.dirname(os.path.realpath(__file__))}/" # Create the Qt application app = QtWidgets.QApplication(sys.argv) diff --git a/pxr/usdImaging/lib/usdviewq/adjustClipping.py b/pxr/usdImaging/lib/usdviewq/adjustClipping.py index 861b67c29d9..9c57bf6cfd1 100644 --- a/pxr/usdImaging/lib/usdviewq/adjustClipping.py +++ b/pxr/usdImaging/lib/usdviewq/adjustClipping.py @@ -102,18 +102,12 @@ def paintEvent(self, paintEvent): def _overrideNearToggled(self, state): """Called when the "Override Near" checkbox is toggled""" self._ui.nearEdit.setEnabled(state) - if state: - self._dataModel.overrideNear = self._nearCache - else: - self._dataModel.overrideNear = None + self._dataModel.overrideNear = self._nearCache if state else None def _overrideFarToggled(self, state): """Called when the "Override Far" checkbox is toggled""" self._ui.farEdit.setEnabled(state) - if state: - self._dataModel.overrideFar = self._farCache - else: - self._dataModel.overrideFar = None + self._dataModel.overrideFar = self._farCache if state else None def _nearChanged(self, text): """Called when the Near text box changed. This can happen when we diff --git a/pxr/usdImaging/lib/usdviewq/appController.py b/pxr/usdImaging/lib/usdviewq/appController.py index 327852758da..44c57881633 100644 --- a/pxr/usdImaging/lib/usdviewq/appController.py +++ b/pxr/usdImaging/lib/usdviewq/appController.py @@ -151,9 +151,7 @@ def __init__(self, mainWindow, parent, name): attributeInspectorWidth = self.stateProperty("attributeInspectorWidth", default=UIDefaults.ATTRIBUTE_INSPECTOR_WIDTH) topHeight = self.stateProperty("topHeight", default=UIDefaults.TOP_HEIGHT) bottomHeight = self.stateProperty("bottomHeight", default=UIDefaults.BOTTOM_HEIGHT) - viewerMode = self.stateProperty("viewerMode", default=False) - - if viewerMode: + if viewerMode := self.stateProperty("viewerMode", default=False): self._mainWindow._ui.primStageSplitter.setSizes([0, 1]) self._mainWindow._ui.topBottomSplitter.setSizes([1, 0]) else: @@ -1050,14 +1048,14 @@ def statusMessage(self, msg, timeout = 0): def editComplete(self, msg): title = self._mainWindow.windowTitle() if title[-1] != '*': - self._mainWindow.setWindowTitle(title + ' *') + self._mainWindow.setWindowTitle(f'{title} *') self.statusMessage(msg, 12) with Timer() as t: if self._stageView: self._stageView.updateView(resetCam=False, forceComputeBBox=True) if self._printTiming: - t.PrintTime("'%s'" % msg) + t.PrintTime(f"'{msg}'") def _openStage(self, usdFilePath, populationMaskPaths): Ar.GetResolver().ConfigureResolverForAsset(usdFilePath) @@ -1099,7 +1097,7 @@ def _GetFormattedError(reasons=[]): sys.stderr.write(_GetFormattedError()) else: if self._printTiming: - t.PrintTime('open stage "%s"' % usdFilePath) + t.PrintTime(f'open stage "{usdFilePath}"') stage.SetEditTarget(stage.GetSessionLayer()) if self._mallocTags == 'stage': @@ -1160,18 +1158,17 @@ def _reloadFixedUI(self, resetStageDataOnly=False): self._UpdateTimeSamples(resetStageDataOnly) def _UpdateTimeSamples(self, resetStageDataOnly=False): - if self.realStartTimeCode is not None and self.realEndTimeCode is not None: - if self.realStartTimeCode > self.realEndTimeCode: - sys.stderr.write('Warning: Invalid frame range (%s, %s)\n' - % (self.realStartTimeCode, self.realEndTimeCode)) - self._timeSamples = [] - else: - self._timeSamples = Drange(self.realStartTimeCode, - self.realEndTimeCode, - self.step) - else: + if self.realStartTimeCode is None or self.realEndTimeCode is None: self._timeSamples = [] + elif self.realStartTimeCode > self.realEndTimeCode: + sys.stderr.write('Warning: Invalid frame range (%s, %s)\n' + % (self.realStartTimeCode, self.realEndTimeCode)) + self._timeSamples = [] + else: + self._timeSamples = Drange(self.realStartTimeCode, + self.realEndTimeCode, + self.step) self._geomCounts = dict() self._hasTimeSamples = (len(self._timeSamples) > 0) self._setPlaybackAvailability() # this sets self._playbackAvailable @@ -1212,39 +1209,40 @@ def _rendererPluginChanged(self, plugin): self._stageView.SetRendererPlugin(plugin) def _configureRendererPlugins(self): - if self._stageView: - self._ui.rendererPluginActionGroup = QtWidgets.QActionGroup(self) - self._ui.rendererPluginActionGroup.setExclusive(True) + if not self._stageView: + return + self._ui.rendererPluginActionGroup = QtWidgets.QActionGroup(self) + self._ui.rendererPluginActionGroup.setExclusive(True) - pluginTypes = self._stageView.GetRendererPlugins() - for pluginType in pluginTypes: - name = self._stageView.GetRendererPluginDisplayName(pluginType) - action = self._ui.menuRendererPlugin.addAction(name) - action.setCheckable(True) - action.pluginType = pluginType - self._ui.rendererPluginActionGroup.addAction(action) - - action.triggered.connect(lambda pluginType=pluginType: - self._rendererPluginChanged(pluginType)) - - # If any plugins exist, set the first one we find supported as the - # default - foundPlugin = False - if len(self._ui.rendererPluginActionGroup.actions()) > 0: - i = 0 - for pluginType in pluginTypes: - if self._stageView.SetRendererPlugin(pluginType): - self._ui.rendererPluginActionGroup.actions()[i].setChecked(True) - foundPlugin = True - break - i += 1 + pluginTypes = self._stageView.GetRendererPlugins() + for pluginType in pluginTypes: + name = self._stageView.GetRendererPluginDisplayName(pluginType) + action = self._ui.menuRendererPlugin.addAction(name) + action.setCheckable(True) + action.pluginType = pluginType + self._ui.rendererPluginActionGroup.addAction(action) - # Otherwise, put a no-op placeholder in. - if not foundPlugin: - action = self._ui.menuRendererPlugin.addAction('Default') - action.setCheckable(True) - action.setChecked(True) - self._ui.rendererPluginActionGroup.addAction(action) + action.triggered.connect(lambda pluginType=pluginType: + self._rendererPluginChanged(pluginType)) + + # If any plugins exist, set the first one we find supported as the + # default + foundPlugin = False + if len(self._ui.rendererPluginActionGroup.actions()) > 0: + i = 0 + for pluginType in pluginTypes: + if self._stageView.SetRendererPlugin(pluginType): + self._ui.rendererPluginActionGroup.actions()[i].setChecked(True) + foundPlugin = True + break + i += 1 + + # Otherwise, put a no-op placeholder in. + if not foundPlugin: + action = self._ui.menuRendererPlugin.addAction('Default') + action.setCheckable(True) + action.setChecked(True) + self._ui.rendererPluginActionGroup.addAction(action) # Topology-dependent UI changes @@ -1385,9 +1383,7 @@ def _resetPrimViewVis(self, selItemsOnly=True, t.PrintTime("update vis column") def _updatePrimView(self): - # Process some more prim view items. - n = min(100, len(self._itemsToPush)) - if n: + if n := min(100, len(self._itemsToPush)): items = self._itemsToPush[-n:] del self._itemsToPush[-n:] for item in items: @@ -1535,7 +1531,7 @@ def _findIndexOfFieldContents(self, field): # don't convert string to float directly because of rounding error frameString = str(field.text()) - if frameString.count(".") == 0: + if "." not in frameString: frameString += ".0" elif frameString[-1] == ".": frameString += "0" @@ -1788,14 +1784,13 @@ def _toggleViewerMode(self): bottomHeight = 0 stageViewWidth += primViewWidth primViewWidth = 0 + elif self._viewerModeEscapeSizes is None: + bottomHeight = UIDefaults.BOTTOM_HEIGHT + topHeight = UIDefaults.TOP_HEIGHT + primViewWidth = UIDefaults.PRIM_VIEW_WIDTH + stageViewWidth = UIDefaults.STAGE_VIEW_WIDTH else: - if self._viewerModeEscapeSizes is not None: - topHeight, bottomHeight, primViewWidth, stageViewWidth = self._viewerModeEscapeSizes - else: - bottomHeight = UIDefaults.BOTTOM_HEIGHT - topHeight = UIDefaults.TOP_HEIGHT - primViewWidth = UIDefaults.PRIM_VIEW_WIDTH - stageViewWidth = UIDefaults.STAGE_VIEW_WIDTH + topHeight, bottomHeight, primViewWidth, stageViewWidth = self._viewerModeEscapeSizes self._ui.topBottomSplitter.setSizes([topHeight, bottomHeight]) self._ui.primStageSplitter.setSizes([primViewWidth, stageViewWidth]) @@ -1986,10 +1981,7 @@ def GrabWindowShot(self): def GrabViewportShot(self): '''Returns a QImage of the current stage view in usdview.''' - if self._stageView: - return self._stageView.grabFrameBuffer() - else: - return None + return self._stageView.grabFrameBuffer() if self._stageView else None # File handling functionality ============================================= @@ -2042,12 +2034,13 @@ def _getSaveFileName(self, caption, recommendedFilename): (saveName, _) = QtWidgets.QFileDialog.getSaveFileName( self._mainWindow, caption, - './' + recommendedFilename, + f'./{recommendedFilename}', 'USD Files (*.usd)' ';;USD ASCII Files (*.usda)' ';;USD Crate Files (*.usdc)' ';;Any USD File (*.usd *.usda *.usdc)', - 'Any USD File (*.usd *.usda *.usdc)') + 'Any USD File (*.usd *.usda *.usdc)', + ) if len(saveName) == 0: return '' @@ -2055,7 +2048,7 @@ def _getSaveFileName(self, caption, recommendedFilename): _, ext = os.path.splitext(saveName) if ext not in ('.usd', '.usda', '.usdc'): saveName += '.usd' - + return saveName def _saveOverridesAs(self): @@ -2141,7 +2134,7 @@ def _reopenStage(self): self._stepSizeChanged() self._stepSizeChanged() except Exception as err: - self.statusMessage('Error occurred reopening Stage: %s' % err) + self.statusMessage(f'Error occurred reopening Stage: {err}') traceback.print_exc() finally: QtWidgets.QApplication.restoreOverrideCursor() @@ -2159,7 +2152,7 @@ def _reloadStage(self): self._reloadFixedUI(resetStageDataOnly=True) self._updateForStageChanges() except Exception as err: - self.statusMessage('Error occurred rereading all layers for Stage: %s' % err) + self.statusMessage(f'Error occurred rereading all layers for Stage: {err}') finally: QtWidgets.QApplication.restoreOverrideCursor() @@ -2276,7 +2269,7 @@ def _updatePropertiesFromPropertyView(self): with self._dataModel.selection.batchComputedPropChanges: self._dataModel.selection.clearComputedProps() - for prop, targets in selectedProperties.items(): + for prop in selectedProperties: if isinstance(prop, CustomAttribute): self._dataModel.selection.addComputedProp(prop) @@ -2351,15 +2344,13 @@ def _refreshAttributeValue(self): self._ui.attributeValueEditor.refresh() def _propertyViewContextMenu(self, point): - item = self._ui.propertyView.itemAt(point) - if item: + if item := self._ui.propertyView.itemAt(point): self.contextMenu = AttributeViewContextMenu(self._mainWindow, item, self._dataModel) self.contextMenu.exec_(QtGui.QCursor.pos()) def _layerStackContextMenu(self, point): - item = self._ui.layerStackView.itemAt(point) - if item: + if item := self._ui.layerStackView.itemAt(point): self.contextMenu = LayerStackContextMenu(self._mainWindow, item) self.contextMenu.exec_(QtGui.QCursor.pos()) @@ -2559,14 +2550,13 @@ def _getItemAtPath(self, path, ensureExpanded=False): path = path if isinstance(path, Sdf.Path) else Sdf.Path(str(path)) parent = self._dataModel.stage.GetPrimAtPath(path) if not parent: - raise RuntimeError("Prim not found at path in stage: %s" % str(path)) + raise RuntimeError(f"Prim not found at path in stage: {str(path)}") pseudoRoot = self._dataModel.stage.GetPseudoRoot() if parent not in self._primToItemMap: # find the first loaded parent childList = [] - while parent != pseudoRoot \ - and not parent in self._primToItemMap: + while parent != pseudoRoot and parent not in self._primToItemMap: childList.append(parent) parent = parent.GetParent() @@ -2611,8 +2601,7 @@ def selectEnclosingModel(self): with self._dataModel.selection.batchPrimChanges: self._dataModel.selection.clearPrims() for prim in oldPrims: - model = GetEnclosingModelPrim(prim) - if model: + if model := GetEnclosingModelPrim(prim): self._dataModel.selection.addPrim(model) else: self._dataModel.selection.addPrim(prim) @@ -2711,12 +2700,13 @@ def _getPrimsFromPaths(self, paths): # Ensure we have an Sdf.Path, not a string. sdfPath = Sdf.Path(str(path)) - prim = self._dataModel.stage.GetPrimAtPath( - sdfPath.GetAbsoluteRootOrPrimPath()) - if not prim: - raise PrimNotFoundException(sdfPath) + if prim := self._dataModel.stage.GetPrimAtPath( + sdfPath.GetAbsoluteRootOrPrimPath() + ): + prims.append(prim) - prims.append(prim) + else: + raise PrimNotFoundException(sdfPath) return prims @@ -2767,7 +2757,7 @@ def _refreshPrimViewSelection(self): selectedItems = [ self._getItemAtPath(prim.GetPath(), ensureExpanded=True) for prim in self._dataModel.selection.getPrims()] - if len(selectedItems) > 0: + if selectedItems: self._ui.primView.setCurrentItem(selectedItems[0]) for item in selectedItems: item.setSelected(True) @@ -2998,12 +2988,12 @@ def _updateAttributeViewInternal(self): treeWidget.clear() self._populateAttributeInspector() - currRow = 0 - for key, attribute in self._attributeDict.iteritems(): + for currRow, (key, attribute) in enumerate(self._attributeDict.iteritems()): targets = None - if (isinstance(attribute, BoundingBoxAttribute) or - isinstance(attribute, LocalToWorldXformAttribute)): + if isinstance( + attribute, (BoundingBoxAttribute, LocalToWorldXformAttribute) + ): typeContent = PropertyViewIcons.COMPOSED() typeRole = PropertyViewDataRoles.COMPOSED elif type(attribute) == Usd.Attribute: @@ -3035,8 +3025,7 @@ def _updateAttributeViewInternal(self): currItem = treeWidget.topLevelItem(currRow) - valTextFont = GetAttributeTextFont(attribute, frame) - if valTextFont: + if valTextFont := GetAttributeTextFont(attribute, frame): currItem.setFont(PropertyViewIndex.VALUE, valTextFont) currItem.setFont(PropertyViewIndex.NAME, valTextFont) else: @@ -3047,8 +3036,7 @@ def _updateAttributeViewInternal(self): currItem.setForeground(PropertyViewIndex.VALUE, fgColor) if targets: - childRow = 0 - for t in targets: + for childRow, t in enumerate(targets): valTextFont = GetAttributeTextFont(attribute, frame) or UIFonts.BOLD # USD does not provide or infer values for relationship or # connection targets, so we don't display them here. @@ -3067,10 +3055,6 @@ def _updateAttributeViewInternal(self): QtCore.Qt.ItemDataRole.WhatsThisRole, PropertyViewDataRoles.CONNECTION) - childRow += 1 - - currRow += 1 - self._updateAttributeViewSelection() # For some reason, resetting the scrollbar position here only works on a @@ -3102,23 +3086,17 @@ def _getSelectedObject(self, selectedAttribute=None): if selectedAttribute: attrName = str(selectedAttribute.text(PropertyViewIndex.NAME)) - if PropTreeWidgetTypeIsRel(selectedAttribute): - obj = self._dataModel.selection.getFocusPrim().GetRelationship( - attrName) - else: - obj = self._dataModel.selection.getFocusPrim().GetAttribute( - attrName) - - return obj - + return ( + self._dataModel.selection.getFocusPrim().GetRelationship(attrName) + if PropTreeWidgetTypeIsRel(selectedAttribute) + else self._dataModel.selection.getFocusPrim().GetAttribute( + attrName + ) + ) return self._dataModel.selection.getFocusPrim() def _findIndentPos(self, s): - for index, char in enumerate(s): - if char != ' ': - return index - - return len(s) - 1 + return next((index for index, char in enumerate(s) if char != ' '), len(s) - 1) def _maxToolTipWidth(self): return 90 @@ -3136,12 +3114,11 @@ def _trimWidth(self, s, isList=False): # which displays the last 5 chars with an ellipsis # in between. For other values, we simply display a # trailing ellipsis to indicate more data. - if s[0] == '\'' and s[-1] == '\'': - return (s[:self._maxToolTipWidth() - offset] - + '...' - + s[len(s) - offset:]) - else: - return s[:self._maxToolTipWidth()] + '...' + return ( + f'{s[:self._maxToolTipWidth() - offset]}...{s[len(s) - offset:]}' + if s[0] == '\'' and s[-1] == '\'' + else f'{s[:self._maxToolTipWidth()]}...' + ) return s def _limitToolTipSize(self, s, isList=False): @@ -3158,7 +3135,7 @@ def _limitToolTipSize(self, s, isList=False): if (len(lines) > self._maxToolTipHeight()): ellipsis = ' '*self._findIndentPos(line) + '...' if isList: - ellipsis = '