Skip to content

Commit

Permalink
Some manual post-2to3 cleanups
Browse files Browse the repository at this point in the history
  • Loading branch information
mhammond committed Jul 5, 2020
1 parent 2316aef commit 9a11ef0
Show file tree
Hide file tree
Showing 27 changed files with 130 additions and 193 deletions.
4 changes: 2 additions & 2 deletions AutoDuck/BuildHHP.py
Expand Up @@ -39,7 +39,7 @@ def handle_globs(lGlobs):
for g in lGlobs:
new = glob.glob(g)
if len(new)==0:
print(("The pattern '%s' yielded no files!" % (g,)))
print("The pattern '%s' yielded no files!" % (g,))
lFiles = lFiles + new
# lFiles is now the list of origin files.
# Normalize all of the paths:
Expand All @@ -65,7 +65,7 @@ def handle_globs(lGlobs):
sCommonPrefix = os.path.normpath(sCommonPrefix) + "\\"
# else we have a trailing slash - it means we _expect_ it to be a patch as-is.
assert os.path.isdir(sCommonPrefix) and sCommonPrefix[-1]=="\\", "commonprefix splitting aint gunna work!"
print(("sCommonPrefix=", sCommonPrefix))
print("sCommonPrefix=", sCommonPrefix)
# Ok, now remove this common prefix from every file:
lRelativeFiles = []
for file in lFiles:
Expand Down
2 changes: 1 addition & 1 deletion AutoDuck/Dump2HHC.py
Expand Up @@ -143,7 +143,7 @@ def parseTopics(cat, input):
raise RuntimeError("What is '%s'" % (top.type,))

if top.name in d:
print(("Duplicate named %s detected: %s" % (top.type, top.name)))
print("Duplicate named %s detected: %s" % (top.type, top.name))

# Skip the property fields line for module/object
line = input.readline()
Expand Down
8 changes: 4 additions & 4 deletions AutoDuck/document_object.py
Expand Up @@ -69,12 +69,12 @@ def GetDocument(fname="pywin32-document.xml"):
doc = GetDocument()
print("Important Notes")
for link in doc.important:
print((" ", link.name, link.href))
print(" ", link.name, link.href)

print("Doc links")
for link in doc.links:
print((" ", link.name, link.href))
print(" ", link.name, link.href)

print("Doc categories")
for c in doc:
print((" ", c.id, c.label))
print(" ", c.id, c.label)
8 changes: 4 additions & 4 deletions AutoDuck/makedfromi.py
Expand Up @@ -80,11 +80,11 @@ def make_doc_summary(inFile, outFile):
extra_tags.append("// " + doc + '\n')
except:
_, msg, _ = sys.exc_info()
print(("Line %d is badly formed - %s" % (lineNo, msg)))
print("Line %d is badly formed - %s" % (lineNo, msg))

lineNo = lineNo + 1

# autoduck seems to crash when > ~97 methods. Loop multiple times,
# autoduck seems to crash when > ~97 methods. Loop multiple times,
# creating a synthetic module name when this happens.
# Hrmph - maybe this was related to the way we generate -
# see rev 1.80 of win32gui.i for a change that prevents this!
Expand All @@ -109,7 +109,7 @@ def make_doc_summary(inFile, outFile):
for (meth, extras) in these_methods:
fields = meth.split('|')
if len(fields)!=3:
print(("**Error - %s does not have enough fields" % meth))
print("**Error - %s does not have enough fields" % meth)
else:
outFile.write("// @pymethod %s|%s|%s|%s\n" % (fields[0],thisModName,fields[1], fields[2]))
for extra in extras:
Expand Down Expand Up @@ -146,7 +146,7 @@ def doit():
except getopt.error:
_, msg, _ = sys.exc_info()
print(msg)
print(("Usage: %s [-o output_name] [-p com_parent] filename" % sys.argv[0]))
print("Usage: %s [-o output_name] [-p com_parent] filename" % sys.argv[0])
return

inName = args[0]
Expand Down
16 changes: 3 additions & 13 deletions AutoDuck/py2d.py
Expand Up @@ -5,19 +5,9 @@
def ad_escape(s):
return re.sub(r"([^<]*)<([^>]*)>", r"\g<1>\\<\g<2>\\>", s)

if sys.version_info[0] >= 3:
# Python3 specific code
type = type
Print = __builtins__.__dict__['print']
long = int
else:
# Python2 specific code
def Print(value, file=sys.stdout):
print(value, file=file)
def next(iter):
# Python3's global next() function
return iter.__next__()

Print = __builtins__.__dict__['print']
long = int

class DocInfo:
def __init__(self, name, ob):
self.name = name
Expand Down
4 changes: 1 addition & 3 deletions Pythonwin/pywin/tools/browser.py
Expand Up @@ -263,7 +263,7 @@ class HLIString(HLIPythonObject):
def IsExpandable(self):
return 0

TypeMap = { type : HLIClass,
TypeMap = { type : HLIClass,
types.FunctionType: HLIFunction,
tuple: HLITuple,
dict: HLIDict,
Expand All @@ -274,8 +274,6 @@ def IsExpandable(self):
types.FrameType : HLIFrame,
types.TracebackType : HLITraceback,
str : HLIString,
str : HLIString,
int: HLIPythonObject,
int: HLIPythonObject,
bool: HLIPythonObject,
float: HLIPythonObject,
Expand Down
22 changes: 3 additions & 19 deletions com/win32com/client/dynamic.py
Expand Up @@ -62,22 +62,14 @@ def debug_attr_print(*args):
print(arg, end=' ')
print()

# A helper to create method objects on the fly
py3k = sys.version_info > (3,0)
if py3k:
def MakeMethod(func, inst, cls):
return types.MethodType(func, inst) # class not needed in py3k
else:
MakeMethod = types.MethodType # all args used in py2k.
def MakeMethod(func, inst, cls):
return types.MethodType(func, inst)

# get the type objects for IDispatch and IUnknown
PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch]
PyIUnknownType = pythoncom.TypeIIDs[pythoncom.IID_IUnknown]

if py3k:
_GoodDispatchTypes=(str, IIDType)
else:
_GoodDispatchTypes=(str, IIDType, str)
_GoodDispatchTypes=(str, IIDType)
_defaultDispatchItem=build.DispatchItem

def _GetGoodDispatch(IDispatch, clsctx = pythoncom.CLSCTX_SERVER):
Expand All @@ -98,17 +90,9 @@ def _GetGoodDispatchAndUserName(IDispatch, userName, clsctx):
# Get a dispatch object, and a 'user name' (ie, the name as
# displayed to the user in repr() etc.
if userName is None:
# Displayed name should be a plain string in py2k, and unicode in py3k
if isinstance(IDispatch, str):
userName = IDispatch
elif not py3k and isinstance(IDispatch, str):
# 2to3 converts the above 'unicode' to 'str', but this will never be executed in py3k
userName = IDispatch.encode("ascii", "replace")
## ??? else userName remains None ???
elif not py3k and isinstance(userName, str):
# 2to3 converts the above 'unicode' to 'str', but this will never be executed in py3k
# As above - always a plain string in py2k
userName = userName.encode("ascii", "replace")
else:
userName = str(userName)
return (_GetGoodDispatch(IDispatch, clsctx), userName)
Expand Down
26 changes: 6 additions & 20 deletions com/win32com/client/genpy.py
Expand Up @@ -476,7 +476,7 @@ def WriteClassBody(self, generator):
defArgDesc = MakeDefaultArgsForPropertyPut(details[2])
print('\t\t"%s": ((%s, LCID, %d, 0),%s),' % (build.MakePublicAttributeName(key), details[0], details[4], defArgDesc), file=stream)
print("\t}", file=stream)

if specialItems["value"]:
entry, invoketype, propArgs = specialItems["value"]
if propArgs is None:
Expand All @@ -488,20 +488,11 @@ def WriteClassBody(self, generator):
print("\t# Default %s for this class is '%s'" % (typename, entry.names[0]), file=stream)
for line in ret:
print(line, file=stream)
if sys.version_info > (3,0):
print("\tdef __str__(self, *args):", file=stream)
print("\t\treturn str(self.__call__(*args))", file=stream)
else:
print("\tdef __unicode__(self, *args):", file=stream)
print("\t\ttry:", file=stream)
print("\t\t\treturn unicode(self.__call__(*args))", file=stream)
print("\t\texcept pythoncom.com_error:", file=stream)
print("\t\t\treturn repr(self)", file=stream)
print("\tdef __str__(self, *args):", file=stream)
print("\t\treturn str(self.__unicode__(*args))", file=stream)
print("\tdef __str__(self, *args):", file=stream)
print("\t\treturn str(self.__call__(*args))", file=stream)
print("\tdef __int__(self, *args):", file=stream)
print("\t\treturn int(self.__call__(*args))", file=stream)

# _NewEnum (DISPID_NEWENUM) does not appear in typelib for many office objects,
# but it can still be retrieved at runtime, so always create __iter__.
# Also, some of those same objects use 1-based indexing, causing the old-style
Expand Down Expand Up @@ -772,7 +763,7 @@ def BuildOleItemsFromType(self):
oleItems[newItem.clsid] = newItem
else:
self.progress.LogWarning("Unknown TKIND found: %d" % infotype)

return oleItems, enumItems, recordItems, vtableItems

def open_writer(self, filename, encoding="mbcs"):
Expand All @@ -788,12 +779,7 @@ def open_writer(self, filename, encoding="mbcs"):
except os.error:
pass
filename = filename + ".temp"
if sys.version_info > (3,0):
ret = open(filename, "wt", encoding=encoding)
else:
import codecs # not available in py3k.
ret = codecs.open(filename, "w", encoding)
return ret
return open(filename, "wt", encoding=encoding)

def finish_writer(self, filename, f, worked):
f.close()
Expand Down
4 changes: 2 additions & 2 deletions com/win32com/servers/interp.py
Expand Up @@ -32,14 +32,14 @@ def __init__(self):
def Eval(self, exp):
"""Evaluate an expression.
"""
if type(exp) not in [str, str]:
if type(exp) != str:
raise Exception(desc="Must be a string",scode=winerror.DISP_E_TYPEMISMATCH)

return eval(str(exp), self.dict)
def Exec(self, exp):
"""Execute a statement.
"""
if type(exp) not in [str, str]:
if type(exp) != str:
raise Exception(desc="Must be a string",scode=winerror.DISP_E_TYPEMISMATCH)
exec(str(exp), self.dict)

Expand Down
20 changes: 10 additions & 10 deletions com/win32com/test/pippo_server.py
Expand Up @@ -10,12 +10,12 @@

class CPippo:
#
# COM declarations
# COM declarations
#
_reg_clsid_ = "{1F0F75D6-BD63-41B9-9F88-2D9D2E1AA5C3}"
_reg_desc_ = "Pippo Python test object"
_reg_progid_ = "Python.Test.Pippo"
#_reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER
#_reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER
###
### Link to typelib
_typelib_guid_ = '{7783054E-9A20-4584-8C62-6ED2A08F6AC6}'
Expand All @@ -42,26 +42,26 @@ def BuildTypelib():
idl = os.path.abspath(os.path.join(this_dir, "pippo.idl"))
tlb=os.path.splitext(idl)[0] + '.tlb'
if newer(idl, tlb):
print(("Compiling %s" % (idl,)))
print("Compiling %s" % (idl,))
rc = os.system ('midl "%s"' % (idl,))
if rc:
raise RuntimeError("Compiling MIDL failed!")
# Can't work out how to prevent MIDL from generating the stubs.
# just nuke them
for fname in "dlldata.c pippo_i.c pippo_p.c pippo.h".split():
os.remove(os.path.join(this_dir, fname))
print(("Registering %s" % (tlb,)))

print("Registering %s" % (tlb,))
tli=pythoncom.LoadTypeLib(tlb)
pythoncom.RegisterTypeLib(tli,tlb)

def UnregisterTypelib():
k = CPippo
try:
pythoncom.UnRegisterTypeLib(k._typelib_guid_,
k._typelib_version_[0],
k._typelib_version_[1],
0,
pythoncom.UnRegisterTypeLib(k._typelib_guid_,
k._typelib_version_[0],
k._typelib_version_[1],
0,
pythoncom.SYS_WIN32)
print("Unregistered typelib")
except pythoncom.error as details:
Expand All @@ -78,7 +78,7 @@ def main(argv=None):
else:
# Build and register the type-libraries.
BuildTypelib()
import win32com.server.register
import win32com.server.register
win32com.server.register.UseCommandLine(CPippo)

if __name__=='__main__':
Expand Down
28 changes: 12 additions & 16 deletions com/win32com/test/testCollections.py
Expand Up @@ -91,27 +91,24 @@ def TestEnum(quiet=None):
try:
o()
raise error("default method with no args worked when it shouldnt have!")
except pythoncom.com_error as xxx_todo_changeme:
(hr, desc, exc, argErr) = xxx_todo_changeme.args
if hr != winerror.DISP_E_BADPARAMCOUNT:
raise error("Expected DISP_E_BADPARAMCOUNT - got %d (%s)" % (hr, desc))
except pythoncom.com_error as exc:
if exc.hresult != winerror.DISP_E_BADPARAMCOUNT:
raise error("Expected DISP_E_BADPARAMCOUNT - got %s" % (exc,))

try:
o.Insert("foo", 2)
raise error("Insert worked when it shouldnt have!")
except pythoncom.com_error as xxx_todo_changeme1:
(hr, desc, exc, argErr) = xxx_todo_changeme1.args
if hr != winerror.DISP_E_TYPEMISMATCH:
raise error("Expected DISP_E_TYPEMISMATCH - got %d (%s)" % (hr, desc))
except pythoncom.com_error as exc:
if exc.hresult != winerror.DISP_E_TYPEMISMATCH:
raise error("Expected DISP_E_TYPEMISMATCH - got %s" % (exc,))

# Remove the sublist for this test!
try:
o.Remove(o.Count())
raise error("Remove worked when it shouldnt have!")
except pythoncom.com_error as xxx_todo_changeme2:
(hr, desc, exc, argErr) = xxx_todo_changeme2.args
if hr != winerror.DISP_E_BADINDEX:
raise error("Expected DISP_E_BADINDEX - got %d (%s)" % (hr, desc))
except pythoncom.com_error as exc:
if exc.hresult != winerror.DISP_E_BADINDEX:
raise error("Expected DISP_E_BADINDEX - got %s" % (exc,))

# Test an empty collection
if not quiet: print("Empty collection test")
Expand All @@ -134,10 +131,9 @@ def TestEnum(quiet=None):
try:
ob = o(0)
raise error("Empty list could be indexed")
except pythoncom.com_error as xxx_todo_changeme3:
(hr, fn, desc, arg) = xxx_todo_changeme3.args
if hr != winerror.DISP_E_BADINDEX:
raise error("Expected DISP_E_BADINDEX - got %d (%s)" % (hr, desc))
except pythoncom.com_error as exc:
if exc.hresult != winerror.DISP_E_BADINDEX:
raise error("Expected DISP_E_BADINDEX - got %s" % (exc,))

class TestCase(win32com.test.util.TestCase):
def testEnum(self):
Expand Down
2 changes: 0 additions & 2 deletions com/win32com/test/testDates.py
@@ -1,5 +1,3 @@
from __future__ import print_function

from datetime import datetime
import unittest

Expand Down
2 changes: 0 additions & 2 deletions com/win32com/test/testIterators.py
@@ -1,5 +1,3 @@
from __future__ import generators

# Some raw iter tests. Some "high-level" iterator tests can be found in
# testvb.py and testOutlook.py
import sys
Expand Down
8 changes: 2 additions & 6 deletions com/win32comext/axscript/client/scriptdispatch.py
Expand Up @@ -44,12 +44,8 @@ def _dynamic_(self, name, lcid, wFlags, args):
realArgs.append(Dispatch(arg))
else:
realArgs.append(arg)
try:
# xxx - todo - work out what code block to pass???
return self.engine.ApplyInScriptedSection(None, func, tuple(realArgs))
except COMException as xxx_todo_changeme:
(hr, msg, exc, arg) = xxx_todo_changeme.args
raise
# xxx - todo - work out what code block to pass???
return self.engine.ApplyInScriptedSection(None, func, tuple(realArgs))

except AttributeError:
if not wFlags & pythoncom.DISPATCH_PROPERTYGET:
Expand Down

0 comments on commit 9a11ef0

Please sign in to comment.