Skip to content

Commit

Permalink
Simplify KeyError fallbacks that don't need to be lazy (#2330)
Browse files Browse the repository at this point in the history
  • Loading branch information
Avasam authored Oct 13, 2024
1 parent 22b0c0a commit 6fa1b68
Show file tree
Hide file tree
Showing 14 changed files with 29 additions and 74 deletions.
2 changes: 1 addition & 1 deletion CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 1 addition & 4 deletions Pythonwin/pywin/Demos/cmdserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
20 changes: 4 additions & 16 deletions com/win32com/client/combrowse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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})"
Expand Down Expand Up @@ -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
Expand Down
5 changes: 1 addition & 4 deletions com/win32com/servers/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 1 addition & 4 deletions com/win32com/test/testExchange.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")


Expand Down
7 changes: 1 addition & 6 deletions com/win32comext/axdebug/adb.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 0 additions & 1 deletion com/win32comext/axdebug/codecontainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 1 addition & 5 deletions com/win32comext/axdebug/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
6 changes: 1 addition & 5 deletions com/win32comext/axscript/client/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
7 changes: 2 additions & 5 deletions com/win32comext/axscript/client/pyscript.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
26 changes: 11 additions & 15 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 1 addition & 4 deletions win32/Lib/netbios.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down
7 changes: 3 additions & 4 deletions win32/Lib/win32serviceutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down
1 change: 1 addition & 0 deletions win32/Lib/win32timezone.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 6fa1b68

Please sign in to comment.