diff --git a/CHANGES.txt b/CHANGES.txt index 13d8b1da2..84b8d5906 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -14,7 +14,7 @@ https://mhammond.github.io/pywin32_installers.html. Coming in build 309, as yet unreleased -------------------------------------- -* Improved handling of dict iterations (removes Python 2 support code, small general speed improvement) (#2332, @Avasam) +* Improved handling of dict iterations and fallbacks (removes Python 2 support code, small general speed improvement) (#2332, #2330, @Avasam) * Fixed "Open GL Demo" (`Pythonwin/pywin/Demos/openGLDemo.py`) and restore "Font" demo in `Pythonwin/pywin/Demos/guidemo.py` (#2345, @Avasam) Build 308, released 2024-10-12 diff --git a/Pythonwin/pywin/Demos/cmdserver.py b/Pythonwin/pywin/Demos/cmdserver.py index 4ec6e49b3..d3e24f401 100644 --- a/Pythonwin/pywin/Demos/cmdserver.py +++ b/Pythonwin/pywin/Demos/cmdserver.py @@ -37,10 +37,7 @@ def unregister(self): def getwriter(self): "Return the current thread's writer, default sys.stdout" - try: - return self.writers[_thread.get_ident()] - except KeyError: - return self.origStdOut + self.writers.get(_thread.get_ident(), self.origStdOut) def write(self, str): "Write to the current thread's writer, default sys.stdout" diff --git a/com/win32com/client/combrowse.py b/com/win32com/client/combrowse.py index 2f7dc4004..d2abacf14 100644 --- a/com/win32com/client/combrowse.py +++ b/com/win32com/client/combrowse.py @@ -265,10 +265,7 @@ class HLITypeLibEntry(HLICOM): def GetText(self): tlb, index = self.myobject name, doc, ctx, helpFile = tlb.GetDocumentation(index) - try: - typedesc = HLITypeKinds[tlb.GetTypeInfoType(index)][1] - except KeyError: - typedesc = "Unknown!" + typedesc = HLITypeKinds.get(tlb.GetTypeInfoType(index), (None, "Unknown!"))[1] return name + " - " + typedesc def GetSubList(self): @@ -448,10 +445,7 @@ def GetText(self): def MakeReturnTypeName(self, typ): justtyp = typ & pythoncom.VT_TYPEMASK - try: - typname = self.vartypes[justtyp] - except KeyError: - typname = "?Bad type?" + typname = self.vartypes.get(justtyp, "?Bad type?") for flag, desc in self.type_flags: if flag & typ: typname = f"{desc}({typname})" @@ -493,15 +487,9 @@ def GetSubList(self): val += f" (Default={default})" ret.append(browser.MakeHLI(val, "Argument")) - try: - fkind = self.funckinds[fd[3]] - except KeyError: - fkind = "Unknown" + fkind = self.funckinds.get(fd[3], "Unknown") ret.append(browser.MakeHLI(fkind, "Function Kind")) - try: - ikind = self.invokekinds[fd[4]] - except KeyError: - ikind = "Unknown" + ikind = self.invokekinds.get([fd[4]], "Unknown") ret.append(browser.MakeHLI(ikind, "Invoke Kind")) # 5 = call conv # 5 = offset vtbl diff --git a/com/win32com/servers/dictionary.py b/com/win32com/servers/dictionary.py index f8a7eb249..cb7eb0279 100644 --- a/com/win32com/servers/dictionary.py +++ b/com/win32com/servers/dictionary.py @@ -85,10 +85,7 @@ def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider): if wFlags & (DISPATCH_METHOD | DISPATCH_PROPERTYGET): if l > 1: raise COMException(scode=winerror.DISP_E_BADPARAMCOUNT) - try: - return self._obj_[key] - except KeyError: - return None # unknown keys return None (VT_NULL) + return self._obj_.get(key) # unknown keys return None (VT_NULL) if l != 2: raise COMException(scode=winerror.DISP_E_BADPARAMCOUNT) diff --git a/com/win32com/test/testExchange.py b/com/win32com/test/testExchange.py index fa2ac5cb0..c20b9c0d4 100644 --- a/com/win32com/test/testExchange.py +++ b/com/win32com/test/testExchange.py @@ -86,10 +86,7 @@ def TestUser(session): print("User has %d fields" % len(fields)) for f in range(len(fields)): field = fields[f + 1] - try: - id = PropTagsById[field.ID] - except KeyError: - id = field.ID + id = PropTagsById.get(field.ID, field.ID) print(f"{field.Name}/{id}={field.Value}") diff --git a/com/win32comext/axdebug/adb.py b/com/win32comext/axdebug/adb.py index b947627c9..191041809 100644 --- a/com/win32comext/axdebug/adb.py +++ b/com/win32comext/axdebug/adb.py @@ -19,12 +19,7 @@ def fnull(*args): pass -try: - os.environ["DEBUG_AXDEBUG"] - debugging = 1 -except KeyError: - debugging = 0 - +debugging = "DEBUG_AXDEBUG" in os.environ traceenter = fnull # trace enter of functions tracev = fnull # verbose trace diff --git a/com/win32comext/axdebug/codecontainer.py b/com/win32comext/axdebug/codecontainer.py index babbd6fc4..e7502845d 100644 --- a/com/win32comext/axdebug/codecontainer.py +++ b/com/win32comext/axdebug/codecontainer.py @@ -197,7 +197,6 @@ def GetCodeContextAtPosition(self, charPos): charPos = self.GetPositionOfLine(lineNo) try: cc = self.codeContexts[charPos] - # trace(" GetContextOfPos using existing") except KeyError: cc = self._MakeContextAtPosition(charPos) self.codeContexts[charPos] = cc diff --git a/com/win32comext/axdebug/util.py b/com/win32comext/axdebug/util.py index 3b4efad93..f3c23523a 100644 --- a/com/win32comext/axdebug/util.py +++ b/com/win32comext/axdebug/util.py @@ -10,11 +10,7 @@ import winerror from win32com.server.exception import COMException -try: - os.environ["DEBUG_AXDEBUG"] - debugging = 1 -except KeyError: - debugging = 0 +debugging = "DEBUG_AXDEBUG" in os.environ def trace(*args): diff --git a/com/win32comext/axscript/client/debug.py b/com/win32comext/axscript/client/debug.py index 554f96095..cceb01db4 100644 --- a/com/win32comext/axscript/client/debug.py +++ b/com/win32comext/axscript/client/debug.py @@ -12,11 +12,7 @@ from win32com.server.exception import COMException from win32com.util import IIDToInterfaceName -try: - os.environ["DEBUG_AXDEBUG"] - debuggingTrace = 1 # Should we print "trace" output? -except KeyError: - debuggingTrace = 0 +debuggingTrace = "DEBUG_AXDEBUG" in os.environ # Should we print "trace" output? def trace(*args): diff --git a/com/win32comext/axscript/client/pyscript.py b/com/win32comext/axscript/client/pyscript.py index 6b9ee53ab..a486b1229 100644 --- a/com/win32comext/axscript/client/pyscript.py +++ b/com/win32comext/axscript/client/pyscript.py @@ -160,15 +160,12 @@ def Register(self): self.attributeObject = NamedScriptAttribute(self) if self.dispatch: # Need to avoid the new Python "lazy" dispatch behaviour. + olerepr, clsid = None try: engine = self.GetEngine() - olerepr = clsid = None typeinfo = self.dispatch.GetTypeInfo() clsid = typeinfo.GetTypeAttr()[0] - try: - olerepr = engine.mapKnownCOMTypes[clsid] - except KeyError: - pass + olerepr = engine.mapKnownCOMTypes.get(clsid) except pythoncom.com_error: typeinfo = None if olerepr is None: diff --git a/setup.py b/setup.py index 0a76dd80b..ce0120e24 100644 --- a/setup.py +++ b/setup.py @@ -820,21 +820,17 @@ def swig_sources(self, sources, ext=None): else: swig_cmd.append("-DSWIG_PY32BIT") target = swig_targets[source] - try: - interface_parent = swig_interface_parents[ - os.path.basename(os.path.splitext(source)[0]) - ] - except KeyError: - # "normal" swig file - no special win32 issues. - pass - else: - # Using win32 extensions to SWIG for generating COM classes. - if interface_parent is not None: - # generating a class, not a module. - swig_cmd.append("-pythoncom") - if interface_parent: - # A class deriving from other than the default - swig_cmd.extend(["-com_interface_parent", interface_parent]) + interface_parent = swig_interface_parents.get( + os.path.basename(os.path.splitext(source)[0]), + None, # "normal" swig file - no special win32 issues. + ) + # Using win32 extensions to SWIG for generating COM classes. + if interface_parent is not None: + # generating a class, not a module. + swig_cmd.append("-pythoncom") + if interface_parent: + # A class deriving from other than the default + swig_cmd.extend(["-com_interface_parent", interface_parent]) # This 'newer' check helps Python 2.2 builds, which otherwise # *always* regenerate the .cpp files, meaning every future diff --git a/win32/Lib/netbios.py b/win32/Lib/netbios.py index fe7f28b36..3da1291c9 100644 --- a/win32/Lib/netbios.py +++ b/win32/Lib/netbios.py @@ -210,10 +210,7 @@ def __init__(self, items): def _pack(self): vals = [] for format, name in self._items: - try: - vals.append(self.__dict__[name]) - except KeyError: - vals.append(None) + vals.append(self.__dict__.get(name)) self._buffer_[:] = struct.pack(*(self._format,) + tuple(vals)) diff --git a/win32/Lib/win32serviceutil.py b/win32/Lib/win32serviceutil.py index 2871b9056..720a5b38d 100644 --- a/win32/Lib/win32serviceutil.py +++ b/win32/Lib/win32serviceutil.py @@ -751,10 +751,9 @@ def HandleCommandLine( "delayed": win32service.SERVICE_AUTO_START, ## ChangeServiceConfig2 called later "disabled": win32service.SERVICE_DISABLED, } - try: - startup = map[val.lower()] - except KeyError: - print("'%s' is not a valid startup option" % val) + startup = map.get(val.lower()) + if not startup: + print(f"{val!r} is not a valid startup option") if val.lower() == "delayed": delayedstart = True elif val.lower() == "auto": diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index 07b30284f..a5b3039f6 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -989,6 +989,7 @@ def get(self, key, default=None): If default is not given, it defaults to None, so that this method never raises a KeyError. """ + # Necessary to use our own __getitem__ and not dict's try: return self[key] except KeyError: