From 945821788a27ad3a86afcb8f83fbbf02c44c38b7 Mon Sep 17 00:00:00 2001 From: Avasam Date: Mon, 24 Jul 2023 09:43:07 -0400 Subject: [PATCH 1/4] Removed rundundant and obsolete references to older python unicode compatibility (#2085) --- Pythonwin/pywin/debugger/debugger.py | 7 +---- Pythonwin/pywin/framework/interact.py | 2 +- Pythonwin/pywin/framework/toolmenu.py | 5 +--- Pythonwin/pywin/idle/PyParse.py | 4 --- Pythonwin/pywin/tools/browser.py | 2 +- Pythonwin/pywin/tools/hierlist.py | 10 ++----- com/win32com/client/makepy.py | 5 +--- com/win32com/server/policy.py | 4 +-- com/win32com/test/testCollections.py | 6 +--- com/win32com/test/testPersist.py | 1 - com/win32com/test/testvb.py | 3 +- com/win32comext/axscript/client/error.py | 17 ----------- win32/Lib/win32gui_struct.py | 37 ++++++------------------ win32/Lib/win32timezone.py | 9 ------ win32/Lib/win32verstamp.py | 6 +--- win32/test/test_clipboard.py | 4 +-- win32/test/test_win32trace.py | 4 --- win32/test/test_win32wnet.py | 2 +- 18 files changed, 23 insertions(+), 105 deletions(-) diff --git a/Pythonwin/pywin/debugger/debugger.py b/Pythonwin/pywin/debugger/debugger.py index 7f2184051..3821854f2 100644 --- a/Pythonwin/pywin/debugger/debugger.py +++ b/Pythonwin/pywin/debugger/debugger.py @@ -26,14 +26,9 @@ from pywin.mfc import afxres, dialog, object, window from pywin.tools import browser, hierlist -# import win32traceutil -if win32ui.UNICODE: - LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW -else: - LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITA - from .dbgcon import * +LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW error = "pywin.debugger.error" diff --git a/Pythonwin/pywin/framework/interact.py b/Pythonwin/pywin/framework/interact.py index 6f86789d2..ed3a7e082 100644 --- a/Pythonwin/pywin/framework/interact.py +++ b/Pythonwin/pywin/framework/interact.py @@ -138,7 +138,7 @@ def ColorizeInteractiveCode(self, cdoc, styleStart, stylePyStart): return state = styleStart # As per comments in Colorize(), we work with the raw utf8 - # bytes. To avoid too muych py3k pain, we treat each utf8 byte + # bytes. To avoid too much pain, we treat each utf8 byte # as a latin-1 unicode character - we only use it to compare # against ascii chars anyway... chNext = cdoc[0:1].decode("latin-1") diff --git a/Pythonwin/pywin/framework/toolmenu.py b/Pythonwin/pywin/framework/toolmenu.py index 17fb908e1..afe06b2b4 100644 --- a/Pythonwin/pywin/framework/toolmenu.py +++ b/Pythonwin/pywin/framework/toolmenu.py @@ -149,10 +149,7 @@ def HandleToolCommand(cmd, code): import commctrl from pywin.mfc import dialog -if win32ui.UNICODE: - LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW -else: - LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITA +LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW class ToolMenuPropPage(dialog.PropertyPage): diff --git a/Pythonwin/pywin/idle/PyParse.py b/Pythonwin/pywin/idle/PyParse.py index 173336cad..97629eee5 100644 --- a/Pythonwin/pywin/idle/PyParse.py +++ b/Pythonwin/pywin/idle/PyParse.py @@ -122,10 +122,6 @@ def dump(*stuff): _tran[ord(ch)] = ")" for ch in "\"'\\\n#": _tran[ord(ch)] = ch -# We are called with unicode strings, and str.translate is one of the few -# py2k functions which can't 'do the right thing' - so take care to ensure -# _tran is full of unicode... -_tran = "".join(_tran) del ch diff --git a/Pythonwin/pywin/tools/browser.py b/Pythonwin/pywin/tools/browser.py index 749018566..188993259 100644 --- a/Pythonwin/pywin/tools/browser.py +++ b/Pythonwin/pywin/tools/browser.py @@ -309,7 +309,7 @@ def GetSubList(self): return ret -# In Python 1.6, strings and Unicode have builtin methods, but we dont really want to see these +# strings and Unicode have builtin methods, but we dont really want to see these class HLIString(HLIPythonObject): def IsExpandable(self): return 0 diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index 341532f57..2ab7f616d 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -106,14 +106,8 @@ def HierInit(self, parent, listControl=None): # Used when window first exists. self.listControl.SetImageList(self.imageList, commctrl.LVSIL_NORMAL) # self.list.AttachObject(self) - ## ??? Need a better way to do this - either some way to detect if it's compiled with UNICODE - ## defined, and/or a way to switch the constants based on UNICODE ??? - if sys.version_info[0] < 3: - parent.HookNotify(self.OnTreeItemExpanding, commctrl.TVN_ITEMEXPANDINGA) - parent.HookNotify(self.OnTreeItemSelChanged, commctrl.TVN_SELCHANGEDA) - else: - parent.HookNotify(self.OnTreeItemExpanding, commctrl.TVN_ITEMEXPANDINGW) - parent.HookNotify(self.OnTreeItemSelChanged, commctrl.TVN_SELCHANGEDW) + parent.HookNotify(self.OnTreeItemExpanding, commctrl.TVN_ITEMEXPANDINGW) + parent.HookNotify(self.OnTreeItemSelChanged, commctrl.TVN_SELCHANGEDW) parent.HookNotify(self.OnTreeItemDoubleClick, commctrl.NM_DBLCLK) self.notify_parent = parent diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index e06e61eb8..901c97429 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -34,10 +34,7 @@ -h -- Do not generate hidden methods. - -u -- Python 1.5 and earlier: Do NOT convert all Unicode objects to - strings. - - Python 1.6 and later: Convert all Unicode objects to strings. + -u -- Convert all Unicode objects to strings. -o -- Create output in a specified output file. If the path leading to the file does not exist, any missing directories will be diff --git a/com/win32com/server/policy.py b/com/win32com/server/policy.py index 4184b0f8c..aba1356dc 100644 --- a/com/win32com/server/policy.py +++ b/com/win32com/server/policy.py @@ -680,9 +680,7 @@ class EventHandlerPolicy(DesignatedWrapPolicy): """The default policy used by event handlers in the win32com.client package. In addition to the base policy, this provides argument conversion semantics for - params - * dispatch params are converted to dispatch objects. - * Unicode objects are converted to strings (1.5.2 and earlier) + params: dispatch params are converted to dispatch objects NOTE: Later, we may allow the object to override this process?? """ diff --git a/com/win32com/test/testCollections.py b/com/win32com/test/testCollections.py index 954697e08..9639c1395 100644 --- a/com/win32com/test/testCollections.py +++ b/com/win32com/test/testCollections.py @@ -5,18 +5,14 @@ # # Also has the side effect of testing some of the PythonCOM error semantics. import sys +import unittest import pythoncom -import pywintypes import win32com.client import win32com.server.util import win32com.test.util import winerror -L = pywintypes.Unicode - -import unittest - error = "collection test error" diff --git a/com/win32com/test/testPersist.py b/com/win32com/test/testPersist.py index 6dde9c168..a75ec6436 100644 --- a/com/win32com/test/testPersist.py +++ b/com/win32com/test/testPersist.py @@ -8,7 +8,6 @@ import win32com.client.dynamic import win32com.server.util import win32ui -from pywintypes import Unicode from win32com import storagecon from win32com.axcontrol import axcontrol from win32com.test.util import CheckClean diff --git a/com/win32com/test/testvb.py b/com/win32com/test/testvb.py index 369bdca85..93590eb57 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -365,8 +365,7 @@ def TestArrays(vbtest, bUseGenerated): testData, list(resultData), ) - # This time, instead of an explicit str() for 1.5, we just - # pass Unicode, so the result should compare equal + # This time, we just pass Unicode, so the result should compare equal testData = [1, 2.0, "3"] resultData, byRefParam = vbtest.PassSAFEARRAYVariant(testData) assert testData == list(byRefParam) diff --git a/com/win32comext/axscript/client/error.py b/com/win32comext/axscript/client/error.py index 285978f76..b92c15741 100644 --- a/com/win32comext/axscript/client/error.py +++ b/com/win32comext/axscript/client/error.py @@ -2,11 +2,9 @@ This contains the core exceptions that the implementations should raise as well as the IActiveScriptError interface code. - """ import re -import sys import traceback import pythoncom @@ -191,21 +189,6 @@ def _BuildFromOther(self, site, exc_type, value, tb): else: bits.extend(traceback.format_exception_only(exc_type, value)) - # XXX - this utf8 encoding seems bogus. From well before py3k, - # we had the comment: - # > all items in the list are utf8 courtesy of Python magically - # > converting unicode to utf8 before compilation. - # but that is likely just confusion from early unicode days; - # Python isn't doing it, pywin32 probably was, so 'mbcs' would - # be the default encoding. We should never hit this these days - # anyway, but on py3k, we *never* will, and str objects there - # don't have a decode method... - if sys.version_info < (3,): - for i in range(len(bits)): - if isinstance(bits[i], str): - # assert isinstance(bits[i], str), type(bits[i]) - bits[i] = bits[i].decode("utf8") - self.description = ExpandTabs("".join(bits)) # Clear tracebacks etc. tb = tb_top = tb_look = None diff --git a/win32/Lib/win32gui_struct.py b/win32/Lib/win32gui_struct.py index 86623ae32..d3406ffc2 100644 --- a/win32/Lib/win32gui_struct.py +++ b/win32/Lib/win32gui_struct.py @@ -60,26 +60,13 @@ def _MakeResult(names_str, values): else: _nmhdr_align_padding = "" -# Encode a string suitable for passing in a win32gui related structure -# If win32gui is built with UNICODE defined (ie, py3k), then functions -# like InsertMenuItem are actually calling InsertMenuItemW etc, so all -# strings will need to be unicode. -if win32gui.UNICODE: - - def _make_text_buffer(text): - # XXX - at this stage win32gui.UNICODE is only True in py3k, - # and in py3k is makes sense to reject bytes. - if not isinstance(text, str): - raise TypeError("MENUITEMINFO text must be unicode") - data = (text + "\0").encode("utf-16le") - return array.array("b", data) - -else: - def _make_text_buffer(text): - if isinstance(text, str): - text = text.encode("mbcs") - return array.array("b", text + "\0") +# Encode a string suitable for passing in a win32gui related structure +def _make_text_buffer(text): + if not isinstance(text, str): + raise TypeError("MENUITEMINFO text must be unicode") + data = (text + "\0").encode("utf-16le") + return array.array("b", data) # make an 'empty' buffer, ready for filling with cch characters. @@ -929,15 +916,9 @@ def PackDEV_BROADCAST_VOLUME(unitmask, flags): def PackDEV_BROADCAST_DEVICEINTERFACE(classguid, name=""): - if win32gui.UNICODE: - # This really means "is py3k?" - so not accepting bytes is OK - if not isinstance(name, str): - raise TypeError("Must provide unicode for the name") - name = name.encode("utf-16le") - else: - # py2k was passed a unicode object - encode as mbcs. - if isinstance(name, str): - name = name.encode("mbcs") + if not isinstance(name, str): + raise TypeError("Must provide unicode for the name") + name = name.encode("utf-16le") # 16 bytes for the IID followed by \0 term'd string. rest_fmt = "16s%ds" % len(name) diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index d0b9a08d1..fb0b36b54 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -888,15 +888,6 @@ def __getitem__(self, filename): def resolveMUITimeZone(spec): """Resolve a multilingual user interface resource for the time zone name - >>> #some pre-amble for the doc-tests to be py2k and py3k aware) - >>> try: unicode and None - ... except NameError: unicode=str - ... - >>> import sys - >>> result = resolveMUITimeZone('@tzres.dll,-110') - >>> expectedResultType = [type(None),unicode][sys.getwindowsversion() >= (6,)] - >>> type(result) is expectedResultType - True spec should be of the format @path,-stringID[;comment] see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details diff --git a/win32/Lib/win32verstamp.py b/win32/Lib/win32verstamp.py index 37aab9e80..074eccb6e 100644 --- a/win32/Lib/win32verstamp.py +++ b/win32/Lib/win32verstamp.py @@ -5,7 +5,6 @@ import optparse import os import struct -import sys from win32api import BeginUpdateResource, EndUpdateResource, UpdateResource @@ -53,10 +52,7 @@ def VS_FIXEDFILEINFO(maj, min, sub, build, debug=0, is_dll=1): def nullterm(s): # get raw bytes for a NULL terminated unicode string. - if sys.version_info[:2] < (3, 7): - return (str(s) + "\0").encode("unicode-internal") - else: - return (str(s) + "\0").encode("utf-16le") + return (str(s) + "\0").encode("utf-16le") def pad32(s, extra=2): diff --git a/win32/test/test_clipboard.py b/win32/test/test_clipboard.py index 5a8623d78..820dd1816 100644 --- a/win32/test/test_clipboard.py +++ b/win32/test/test_clipboard.py @@ -74,8 +74,8 @@ def test_unicode(self): def test_unicode_text(self): val = "test-val" SetClipboardText(val) - # GetClipboardData doesn't to auto string conversions - so on py3k, - # CF_TEXT returns bytes. + # GetClipboardData doesn't do auto string conversions - + # so CF_TEXT returns bytes. expected = val.encode("latin1") self.assertEqual(GetClipboardData(win32con.CF_TEXT), expected) SetClipboardText(val, win32con.CF_UNICODETEXT) diff --git a/win32/test/test_win32trace.py b/win32/test/test_win32trace.py index 8b241cbbd..b06a83462 100644 --- a/win32/test/test_win32trace.py +++ b/win32/test/test_win32trace.py @@ -120,8 +120,6 @@ def testRoundTrip(self): def testRoundTripUnicode(self): win32trace.write("\xa9opyright Syver Enstad") syverEnstad = win32trace.read() - # str objects are always returned in py2k (latin-1 encoding was used - # on unicode objects) self.assertEqual("\xa9opyright Syver Enstad", syverEnstad) def testBlockingRead(self): @@ -130,8 +128,6 @@ def testBlockingRead(self): def testBlockingReadUnicode(self): win32trace.write("\xa9opyright Syver Enstad") - # str objects are always returned in py2k (latin-1 encoding was used - # on unicode objects) self.assertEqual("\xa9opyright Syver Enstad", win32trace.blockingread()) def testFlush(self): diff --git a/win32/test/test_win32wnet.py b/win32/test/test_win32wnet.py index 11769fc92..cd0e13f4b 100644 --- a/win32/test/test_win32wnet.py +++ b/win32/test/test_win32wnet.py @@ -64,7 +64,7 @@ def _checkItemAttributes(self, item, attrs): new_val = val + 1 elif typ is str: if val is not None: - # on py2k, must be string or unicode. py3k must be string or bytes. + # must be string self.assertTrue( isinstance(val, str), "Attr %r has value %r" % (attr, val) ) From 3a22ca6e0cb9328fcc9ee7a0dc61f7d18a112520 Mon Sep 17 00:00:00 2001 From: Avasam Date: Mon, 24 Jul 2023 09:48:27 -0400 Subject: [PATCH 2/4] remove obsolete aliases except unicode-related in non-adodbapi code (#2087) --- AutoDuck/py2d.py | 1 - Pythonwin/pywin/framework/stdin.py | 15 ++++---- Pythonwin/pywin/idle/AutoIndent.py | 15 ++------ Pythonwin/pywin/mfc/activex.py | 9 +---- com/win32com/client/__init__.py | 14 ++------ com/win32com/client/genpy.py | 32 ++++++++--------- com/win32com/test/testPyComTest.py | 3 +- com/win32com/test/testShell.py | 16 +++------ com/win32com/test/testvb.py | 5 ++- com/win32comext/mapi/mapiutil.py | 21 +++++------ isapi/samples/redirector.py | 25 +++++--------- win32/Demos/BackupRead_BackupWrite.py | 5 ++- win32/Lib/netbios.py | 15 ++------ win32/Lib/pywin32_testutil.py | 22 ------------ win32/Lib/win32gui_struct.py | 50 +++++++-------------------- win32/test/handles.py | 8 ++--- win32/test/test_odbc.py | 12 +++---- win32/test/test_pywintypes.py | 3 +- win32/test/test_security.py | 6 ++-- win32/test/test_win32file.py | 5 --- win32/test/test_win32wnet.py | 4 +-- 21 files changed, 81 insertions(+), 205 deletions(-) diff --git a/AutoDuck/py2d.py b/AutoDuck/py2d.py index 7b3f641ef..7dda5d8d2 100644 --- a/AutoDuck/py2d.py +++ b/AutoDuck/py2d.py @@ -8,7 +8,6 @@ def ad_escape(s): Print = __builtins__.__dict__["print"] -long = int class DocInfo: diff --git a/Pythonwin/pywin/framework/stdin.py b/Pythonwin/pywin/framework/stdin.py index b08311083..26c8895fd 100644 --- a/Pythonwin/pywin/framework/stdin.py +++ b/Pythonwin/pywin/framework/stdin.py @@ -5,7 +5,7 @@ # any purpose. """Provides a class Stdin which can be used to emulate the regular old sys.stdin for the PythonWin interactive window. Right now it just pops -up a raw_input() dialog. With luck, someone will integrate it into the +up a input() dialog. With luck, someone will integrate it into the actual PythonWin interactive window someday. WARNING: Importing this file automatically replaces sys.stdin with an @@ -18,15 +18,12 @@ """ import sys -try: - get_input_line = raw_input # py2x -except NameError: - get_input_line = input # py3k +get_input_line = input class Stdin: def __init__(self): - self.real_file = sys.stdin # NOTE: Likely to be None in py3k + self.real_file = sys.stdin # NOTE: Likely to be None self.buffer = "" self.closed = False @@ -142,7 +139,7 @@ def readlines(self, *sizehint): Sell you soul to the devil, baby """ - def fake_raw_input(prompt=None): + def fake_input(prompt=None): """Replacement for raw_input() which pulls lines out of global test_input. For testing only! """ @@ -157,7 +154,7 @@ def fake_raw_input(prompt=None): raise EOFError() return result - get_input_line = fake_raw_input + get_input_line = fake_input # Some completely inadequate tests, just to make sure the code's not totally broken try: @@ -169,6 +166,6 @@ def fake_raw_input(prompt=None): print(x.readline(3)) print(x.readlines()) finally: - get_input_line = raw_input + get_input_line = input else: sys.stdin = Stdin() diff --git a/Pythonwin/pywin/idle/AutoIndent.py b/Pythonwin/pywin/idle/AutoIndent.py index c5adc5f86..0ed506e5a 100644 --- a/Pythonwin/pywin/idle/AutoIndent.py +++ b/Pythonwin/pywin/idle/AutoIndent.py @@ -1,20 +1,9 @@ -import sys import tokenize from pywin import default_scintilla_encoding from . import PyParse -if sys.version_info < (3,): - # in py2k, tokenize() takes a 'token eater' callback, while - # generate_tokens is a generator that works with str objects. - token_generator = tokenize.generate_tokens -else: - # in py3k tokenize() is the generator working with 'byte' objects, and - # token_generator is the 'undocumented b/w compat' function that - # theoretically works with str objects - but actually seems to fail) - token_generator = tokenize.tokenize - class AutoIndent: menudefs = [ @@ -516,7 +505,7 @@ def readline(self): val = "" else: val = self.text.get(mark, mark + " lineend+1c") - # hrm - not sure this is correct in py3k - the source code may have + # hrm - not sure this is correct - the source code may have # an encoding declared, but the data will *always* be in # default_scintilla_encoding - so if anyone looks at the encoding decl # in the source they will be wrong. I think. Maybe. Or something... @@ -531,7 +520,7 @@ def run(self): tokenize.tabsize = self.tabwidth try: try: - for typ, token, start, end, line in token_generator(self.readline): + for typ, token, start, end, line in tokenize.tokenize(self.readline): if typ == NAME and token in OPENERS: self.blkopenline = line elif typ == INDENT and self.blkopenline: diff --git a/Pythonwin/pywin/mfc/activex.py b/Pythonwin/pywin/mfc/activex.py index 596bbef5e..a9828e78d 100644 --- a/Pythonwin/pywin/mfc/activex.py +++ b/Pythonwin/pywin/mfc/activex.py @@ -5,13 +5,6 @@ from . import window -# XXX - we are still "classic style" classes in py2x, so we need can't yet -# use 'type()' everywhere - revisit soon, as py2x will move to new-style too... -try: - from types import ClassType as new_type -except ImportError: - new_type = type # py3k - class Control(window.Wnd): """An ActiveX control base class. A new class must be derived from both @@ -78,7 +71,7 @@ def MakeControlClass(controlClass, name=None): """ if name is None: name = controlClass.__name__ - return new_type("OCX" + name, (Control, controlClass), {}) + return type("OCX" + name, (Control, controlClass), {}) def MakeControlInstance(controlClass, name=None): diff --git a/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index 2a6b7d1c9..3ce112046 100644 --- a/com/win32com/client/__init__.py +++ b/com/win32com/client/__init__.py @@ -332,16 +332,10 @@ class object that derives from three classes: # If the clsid was an object, get the clsid clsid = disp_class.CLSID # Create a new class that derives from 3 classes - the dispatch class, the event sink class and the user class. - # XXX - we are still "classic style" classes in py2x, so we need can't yet - # use 'type()' everywhere - revisit soon, as py2x will move to new-style too... - try: - from types import ClassType as new_type - except ImportError: - new_type = type # py3k events_class = getevents(clsid) if events_class is None: raise ValueError("This COM object does not support events.") - result_class = new_type( + result_class = type( "COMEventClass", (disp_class, events_class, user_event_class), {"__setattr__": _event_setattr_}, @@ -401,14 +395,10 @@ def WithEvents(disp, user_event_class): clsid = disp_class.CLSID # Create a new class that derives from 2 classes - the event sink # class and the user class. - try: - from types import ClassType as new_type - except ImportError: - new_type = type # py3k events_class = getevents(clsid) if events_class is None: raise ValueError("This COM object does not support events.") - result_class = new_type("COMEventClass", (events_class, user_event_class), {}) + result_class = type("COMEventClass", (events_class, user_event_class), {}) instance = result_class(disp) # This only calls the first base class __init__. if hasattr(user_event_class, "__init__"): user_event_class.__init__(instance) diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index 8cda87deb..a49481524 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -34,22 +34,22 @@ # does not use this map at runtime - all Alias/Enum have already # been translated. mapVTToTypeString = { - pythoncom.VT_I2: "types.IntType", - pythoncom.VT_I4: "types.IntType", - pythoncom.VT_R4: "types.FloatType", - pythoncom.VT_R8: "types.FloatType", - pythoncom.VT_BSTR: "types.StringType", - pythoncom.VT_BOOL: "types.IntType", - pythoncom.VT_VARIANT: "types.TypeType", - pythoncom.VT_I1: "types.IntType", - pythoncom.VT_UI1: "types.IntType", - pythoncom.VT_UI2: "types.IntType", - pythoncom.VT_UI4: "types.IntType", - pythoncom.VT_I8: "types.LongType", - pythoncom.VT_UI8: "types.LongType", - pythoncom.VT_INT: "types.IntType", - pythoncom.VT_DATE: "pythoncom.PyTimeType", - pythoncom.VT_UINT: "types.IntType", + pythoncom.VT_I2: "int", + pythoncom.VT_I4: "int", + pythoncom.VT_R4: "float", + pythoncom.VT_R8: "float", + pythoncom.VT_BSTR: "str", + pythoncom.VT_BOOL: "int", + pythoncom.VT_VARIANT: "type", + pythoncom.VT_I1: "int", + pythoncom.VT_UI1: "int", + pythoncom.VT_UI2: "int", + pythoncom.VT_UI4: "int", + pythoncom.VT_I8: "int", + pythoncom.VT_UI8: "int", + pythoncom.VT_INT: "int", + pythoncom.VT_DATE: "datetime.date", + pythoncom.VT_UINT: "int", } diff --git a/com/win32com/test/testPyComTest.py b/com/win32com/test/testPyComTest.py index e7b065b23..59b601bc6 100644 --- a/com/win32com/test/testPyComTest.py +++ b/com/win32com/test/testPyComTest.py @@ -16,7 +16,6 @@ import win32com.client.connect import win32timezone import winerror -from pywin32_testutil import str2memory from win32com.client import VARIANT, CastTo, DispatchBaseClass, constants from win32com.test.util import CheckClean, RegisterPythonServer @@ -264,7 +263,7 @@ def TestCommon(o, is_generated): ) # and binary - TestApplyResult(o.SetBinSafeArray, (str2memory("foo\0bar"),), 7) + TestApplyResult(o.SetBinSafeArray, (memoryview(b"foo\0bar"),), 7) progress("Checking properties") o.LongProp = 3 diff --git a/com/win32com/test/testShell.py b/com/win32com/test/testShell.py index d6a164caa..3d1b51b89 100644 --- a/com/win32com/test/testShell.py +++ b/com/win32com/test/testShell.py @@ -3,17 +3,11 @@ import struct import sys -import win32timezone - -try: - sys_maxsize = sys.maxsize # 2.6 and later - maxsize != maxint on 64bits -except AttributeError: - sys_maxsize = sys.maxint - import pythoncom import pywintypes import win32com.test.util import win32con +import win32timezone from win32com.shell import shell from win32com.shell.shellcon import * from win32com.storagecon import * @@ -168,7 +162,7 @@ def testComplex(self): ftCreationTime=ctime, ftLastAccessTime=atime, ftLastWriteTime=wtime, - nFileSize=sys_maxsize + 1, + nFileSize=sys.maxsize + 1, ) self._testRT(d) @@ -184,7 +178,7 @@ def testUnicode(self): ftCreationTime=ctime, ftLastAccessTime=atime, ftLastWriteTime=wtime, - nFileSize=sys_maxsize + 1, + nFileSize=sys.maxsize + 1, ), dict( cFileName="foo2.txt", @@ -194,7 +188,7 @@ def testUnicode(self): ftCreationTime=ctime, ftLastAccessTime=atime, ftLastWriteTime=wtime, - nFileSize=sys_maxsize + 1, + nFileSize=sys.maxsize + 1, ), dict( cFileName="foo\xa9.txt", @@ -204,7 +198,7 @@ def testUnicode(self): ftCreationTime=ctime, ftLastAccessTime=atime, ftLastWriteTime=wtime, - nFileSize=sys_maxsize + 1, + nFileSize=sys.maxsize + 1, ), ] s = shell.FILEGROUPDESCRIPTORAsString(d, 1) diff --git a/com/win32com/test/testvb.py b/com/win32com/test/testvb.py index 93590eb57..46d0f08f0 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -11,7 +11,6 @@ import win32com.client.dynamic import win32com.client.gencache import winerror -from pywin32_testutil import str2memory from win32com.server.util import NewCollection, wrap from win32com.test import util @@ -86,8 +85,8 @@ def TestVB(vbtest, bUseGenerated): vbtest.VariantProperty = 10 if vbtest.VariantProperty != 10: raise error("Could not set the variant integer property correctly.") - vbtest.VariantProperty = str2memory("raw\0data") - if vbtest.VariantProperty != str2memory("raw\0data"): + vbtest.VariantProperty = memoryview(b"raw\0data") + if vbtest.VariantProperty != memoryview(b"raw\0data"): raise error("Could not set the variant buffer property correctly.") vbtest.StringProperty = "Hello from Python" if vbtest.StringProperty != "Hello from Python": diff --git a/com/win32comext/mapi/mapiutil.py b/com/win32comext/mapi/mapiutil.py index 8a5ffb632..b0f20dc88 100644 --- a/com/win32comext/mapi/mapiutil.py +++ b/com/win32comext/mapi/mapiutil.py @@ -1,8 +1,5 @@ # General utilities for MAPI and MAPI objects. # We used to use these old names from the 'types' module... -TupleType = tuple -ListType = list -IntType = int import pythoncom from pywintypes import TimeType @@ -103,13 +100,13 @@ def GetProperties(obj, propList): If the property fetch fails, the result is None. """ bRetList = 1 - if not isinstance(propList, (TupleType, ListType)): + if not isinstance(propList, (tuple, list)): bRetList = 0 propList = (propList,) realPropList = [] rc = [] for prop in propList: - if not isinstance(prop, IntType): # Integer + if not isinstance(prop, int): props = ((mapi.PS_PUBLIC_STRINGS, prop),) propIds = obj.GetIDsFromNames(props, 0) prop = mapitags.PROP_TAG( @@ -145,19 +142,17 @@ def GetAllProperties(obj, make_tag_names=True): _MapiTypeMap = { - type(0.0): mapitags.PT_DOUBLE, - type(0): mapitags.PT_I4, - type(b""): mapitags.PT_STRING8, # bytes - type(""): mapitags.PT_UNICODE, # str + float: mapitags.PT_DOUBLE, + int: mapitags.PT_I4, + bytes: mapitags.PT_STRING8, + str: mapitags.PT_UNICODE, type(None): mapitags.PT_UNSPECIFIED, - # In Python 2.2.2, bool isn't a distinct type (type(1==1) is type(0)). - # (markh thinks the above is trying to say that in 2020, we probably *do* - # want bool in this map? :) + bool: mapitags.PT_BOOLEAN, } def SetPropertyValue(obj, prop, val): - if not isinstance(prop, IntType): + if not isinstance(prop, int): props = ((mapi.PS_PUBLIC_STRINGS, prop),) propIds = obj.GetIDsFromNames(props, mapi.MAPI_CREATE) if val == (1 == 1) or val == (1 == 0): diff --git a/isapi/samples/redirector.py b/isapi/samples/redirector.py index 40698bb2c..da62d4022 100644 --- a/isapi/samples/redirector.py +++ b/isapi/samples/redirector.py @@ -17,17 +17,12 @@ # any excludes. import sys - -from isapi import isapicon, threaded_extension - -try: - from urllib.request import urlopen -except ImportError: - # py3k spelling... - from urllib.request import urlopen +from urllib.request import urlopen import win32api +from isapi import isapicon, threaded_extension + # sys.isapidllhandle will exist when we are loaded by the IIS framework. # In this case we redirect our output to the win32traceutil collector. if hasattr(sys, "isapidllhandle"): @@ -84,15 +79,11 @@ def Dispatch(self, ecb): print("Opening %s" % new_url) fp = urlopen(new_url) headers = fp.info() - # subtle py3k breakage: in py3k, str(headers) has normalized \r\n - # back to \n and also stuck an extra \n term. py2k leaves the - # \r\n from the server in tact and finishes with a single term. - if sys.version_info < (3, 0): - header_text = str(headers) + "\r\n" - else: - # take *all* trailing \n off, replace remaining with - # \r\n, then add the 2 trailing \r\n. - header_text = str(headers).rstrip("\n").replace("\n", "\r\n") + "\r\n\r\n" + # subtle breakage: str(headers) normalizes \r\n + # back to \n and also sticks an extra \n term. + # take *all* trailing \n off, replace remaining with + # \r\n, then add the 2 trailing \r\n. + header_text = str(headers).rstrip("\n").replace("\n", "\r\n") + "\r\n\r\n" ecb.SendResponseHeaders("200 OK", header_text, False) ecb.WriteClient(fp.read()) ecb.DoneWithSession() diff --git a/win32/Demos/BackupRead_BackupWrite.py b/win32/Demos/BackupRead_BackupWrite.py index 1f88af8fd..02aae9103 100644 --- a/win32/Demos/BackupRead_BackupWrite.py +++ b/win32/Demos/BackupRead_BackupWrite.py @@ -8,7 +8,6 @@ import win32con import win32file import win32security -from pywin32_testutil import ob2memory from win32com import storagecon all_sd_info = ( @@ -115,7 +114,7 @@ open(tempfile + ":anotherstream").read() == open(outfile + ":anotherstream").read() ), "anotherstream contents differ !" assert ( - ob2memory(win32security.GetFileSecurity(tempfile, all_sd_info))[:] - == ob2memory(win32security.GetFileSecurity(outfile, all_sd_info))[:] + memoryview(win32security.GetFileSecurity(tempfile, all_sd_info))[:] + == memoryview(win32security.GetFileSecurity(outfile, all_sd_info))[:] ), "Security descriptors are different !" ## also should check Summary Info programatically diff --git a/win32/Lib/netbios.py b/win32/Lib/netbios.py index c2e663868..3f80b6b62 100644 --- a/win32/Lib/netbios.py +++ b/win32/Lib/netbios.py @@ -1,5 +1,4 @@ import struct -import sys import win32wnet @@ -266,14 +265,6 @@ def ACTION_HEADER(): return NCBStruct(ACTION_HEADER_ITEMS) -def byte_to_int(b): - """Given an element in a binary buffer, return its integer value""" - if sys.version_info >= (3, 0): - # a byte is already an int in py3k - return b - return ord(b) # its a char from a string in py2k. - - if __name__ == "__main__": # code ported from "HOWTO: Get the MAC Address for an Ethernet Adapter" # MS KB ID: Q118623 @@ -287,18 +278,18 @@ def byte_to_int(b): for i in range(la_enum.length): ncb.Reset() ncb.Command = NCBRESET - ncb.Lana_num = byte_to_int(la_enum.lana[i]) + ncb.Lana_num = la_enum.lana[i] rc = Netbios(ncb) if rc != 0: raise RuntimeError("Unexpected result %d" % (rc,)) ncb.Reset() ncb.Command = NCBASTAT - ncb.Lana_num = byte_to_int(la_enum.lana[i]) + ncb.Lana_num = la_enum.lana[i] ncb.Callname = b"* " adapter = ADAPTER_STATUS() ncb.Buffer = adapter Netbios(ncb) print("Adapter address:", end=" ") for ch in adapter.adapter_address: - print("%02x" % (byte_to_int(ch),), end=" ") + print("%02x" % (ch,), end=" ") print() diff --git a/win32/Lib/pywin32_testutil.py b/win32/Lib/pywin32_testutil.py index 42d41f3ec..63cd87ea2 100644 --- a/win32/Lib/pywin32_testutil.py +++ b/win32/Lib/pywin32_testutil.py @@ -7,28 +7,6 @@ import winerror -## -## General purpose utilities for the test suite. -## - - -# Sometimes we want to pass a string that should explicitly be treated as -# a memory blob. -def str2memory(sval): - if sys.version_info < (3, 0): - return buffer(sval) - # py3k. - return memoryview(sval.encode("latin1")) - - -# Sometimes we want to pass an object that exposes its memory -def ob2memory(ob): - if sys.version_info < (3, 0): - return buffer(ob) - # py3k. - return memoryview(ob) - - ## ## unittest related stuff ## diff --git a/win32/Lib/win32gui_struct.py b/win32/Lib/win32gui_struct.py index d3406ffc2..bf4c9c6be 100644 --- a/win32/Lib/win32gui_struct.py +++ b/win32/Lib/win32gui_struct.py @@ -30,28 +30,21 @@ import array import struct import sys +from collections import namedtuple import commctrl import pywintypes import win32con import win32gui -is64bit = "64 bit" in sys.version - -try: - from collections import namedtuple - - def _MakeResult(names_str, values): - names = names_str.split() - nt = namedtuple(names[0], names[1:]) - return nt(*values) -except ImportError: - # no namedtuple support - just return the values as a normal tuple. - def _MakeResult(names_str, values): - return values +def _MakeResult(names_str, values): + names = names_str.split() + nt = namedtuple(names[0], names[1:]) + return nt(*values) +is64bit = "64 bit" in sys.version _nmhdr_fmt = "PPi" if is64bit: # When the item past the NMHDR gets aligned (eg, when it is a struct) @@ -74,23 +67,6 @@ def _make_empty_text_buffer(cch): return _make_text_buffer("\0" * cch) -if sys.version_info < (3, 0): - - def _make_memory(ob): - return str(buffer(ob)) - - def _make_bytes(sval): - return sval - -else: - - def _make_memory(ob): - return bytes(memoryview(ob)) - - def _make_bytes(sval): - return sval.encode("ascii") - - # Generic WM_NOTIFY unpacking def UnpackWMNOTIFY(lparam): format = "PPi" @@ -885,11 +861,11 @@ def PackHDITEM( # Generic function for packing a DEV_BROADCAST_* structure - generally used # by the other PackDEV_BROADCAST_* functions in this module. -def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=_make_bytes("")): +def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=b""): # It seems a requirement is 4 byte alignment, even for the 'BYTE data[1]' # field (eg, that would make DEV_BROADCAST_HANDLE 41 bytes, but we must # be 44. - extra_data += _make_bytes("\0" * (4 - len(extra_data) % 4)) + extra_data += b"\0" * (4 - len(extra_data) % 4) format = "iii" + rest_fmt full_size = struct.calcsize(format) + len(extra_data) data = (full_size, devicetype, 0) + rest_data @@ -899,14 +875,14 @@ def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=_make_bytes("" def PackDEV_BROADCAST_HANDLE( handle, hdevnotify=0, - guid=_make_bytes("\0" * 16), + guid=b"\0" * 16, name_offset=0, - data=_make_bytes("\0"), + data=b"\0", ): return PackDEV_BROADCAST( win32con.DBT_DEVTYP_HANDLE, "PP16sl", - (int(handle), int(hdevnotify), _make_memory(guid), name_offset), + (int(handle), int(hdevnotify), bytes(memoryview(guid)), name_offset), data, ) @@ -922,8 +898,8 @@ def PackDEV_BROADCAST_DEVICEINTERFACE(classguid, name=""): # 16 bytes for the IID followed by \0 term'd string. rest_fmt = "16s%ds" % len(name) - # _make_memory(iid) hoops necessary to get the raw IID bytes. - rest_data = (_make_memory(pywintypes.IID(classguid)), name) + # bytes(memoryview(iid)) hoops necessary to get the raw IID bytes. + rest_data = (bytes(memoryview(pywintypes.IID(classguid))), name) return PackDEV_BROADCAST(win32con.DBT_DEVTYP_DEVICEINTERFACE, rest_fmt, rest_data) diff --git a/win32/test/handles.py b/win32/test/handles.py index 98b73625d..b1f2240ba 100644 --- a/win32/test/handles.py +++ b/win32/test/handles.py @@ -138,17 +138,13 @@ def testHandleNonZero(self): self.assertTrue(h) def testLong(self): - # sys.maxint+1 should always be a 'valid' handle, treated as an + # sys.maxsize+1 should always be a 'valid' handle, treated as an # unsigned int, even though it is a long. Although pywin32 should not # directly create such longs, using struct.unpack() with a P format # may well return them. eg: # >>> struct.unpack("P", struct.pack("P", -1)) # (4294967295L,) - try: - big = sys.maxsize - except AttributeError: - big = sys.maxint - pywintypes.HANDLE(big + 1) + pywintypes.HANDLE(sys.maxsize + 1) def testGC(self): # This used to provoke: diff --git a/win32/test/test_odbc.py b/win32/test/test_odbc.py index 808ebfce1..8cba6310f 100644 --- a/win32/test/test_odbc.py +++ b/win32/test/test_odbc.py @@ -6,7 +6,7 @@ import odbc import pythoncom -from pywin32_testutil import TestSkipped, str2memory +from pywin32_testutil import TestSkipped from win32com.client import constants # We use the DAO ODBC driver @@ -185,11 +185,7 @@ def testBit(self): def testInt(self): self._test_val("intfield", 1) self._test_val("intfield", 0) - try: - big = sys.maxsize - except AttributeError: - big = sys.maxint - self._test_val("intfield", big) + self._test_val("intfield", sys.maxsize) def testFloat(self): self._test_val("floatfield", 1.01) @@ -206,11 +202,11 @@ def testLongVarchar(self): def testLongBinary(self): """Test a long raw field in excess of internal cursor data size (65536)""" - self._test_val("longbinaryfield", str2memory("\0\1\2" * 70000)) + self._test_val("longbinaryfield", memoryview(b"\0\1\2" * 70000)) def testRaw(self): ## Test binary data - self._test_val("rawfield", str2memory("\1\2\3\4\0\5\6\7\8")) + self._test_val("rawfield", memoryview(b"\1\2\3\4\0\5\6\7\8")) def test_widechar(self): """Test a unicode character that would be mangled if bound as plain character. diff --git a/win32/test/test_pywintypes.py b/win32/test/test_pywintypes.py index 1f9cd9e7d..35962be32 100644 --- a/win32/test/test_pywintypes.py +++ b/win32/test/test_pywintypes.py @@ -5,7 +5,6 @@ import unittest import pywintypes -from pywin32_testutil import ob2memory class TestCase(unittest.TestCase): @@ -85,7 +84,7 @@ def testPyTimeTooLarge(self): def testGUID(self): s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) - iid2 = pywintypes.IID(ob2memory(iid), True) + iid2 = pywintypes.IID(memoryview(iid), True) self.assertEqual(iid, iid2) self.assertRaises(ValueError, pywintypes.IID, b"00", True) # too short self.assertRaises(TypeError, pywintypes.IID, 0, True) # no buffer diff --git a/win32/test/test_security.py b/win32/test/test_security.py index dc80fb429..52be9f328 100644 --- a/win32/test/test_security.py +++ b/win32/test/test_security.py @@ -7,7 +7,7 @@ import win32con import win32security import winerror -from pywin32_testutil import TestSkipped, ob2memory, testmain +from pywin32_testutil import TestSkipped, testmain class SecurityTests(unittest.TestCase): @@ -53,8 +53,8 @@ def testBuffer(self): if self.admin_sid is None: raise TestSkipped("No 'Administrator' account is available") self.assertEqual( - ob2memory(win32security.LookupAccountName("", "Administrator")[0]), - ob2memory(win32security.LookupAccountName("", "Administrator")[0]), + memoryview(win32security.LookupAccountName("", "Administrator")[0]), + memoryview(win32security.LookupAccountName("", "Administrator")[0]), ) def testMemory(self): diff --git a/win32/test/test_win32file.py b/win32/test/test_win32file.py index 3784bfed1..c57e94ad5 100644 --- a/win32/test/test_win32file.py +++ b/win32/test/test_win32file.py @@ -19,11 +19,6 @@ import winerror from pywin32_testutil import TestSkipped, testmain -try: - set -except NameError: - from sets import Set as set - class TestReadBuffer(unittest.TestCase): def testLen(self): diff --git a/win32/test/test_win32wnet.py b/win32/test/test_win32wnet.py index cd0e13f4b..316c2e29d 100644 --- a/win32/test/test_win32wnet.py +++ b/win32/test/test_win32wnet.py @@ -107,12 +107,12 @@ def testNetbios(self): for i in range(la_enum.length): ncb.Reset() ncb.Command = netbios.NCBRESET - ncb.Lana_num = netbios.byte_to_int(la_enum.lana[i]) + ncb.Lana_num = la_enum.lana[i] rc = Netbios(ncb) self.assertEqual(rc, 0) ncb.Reset() ncb.Command = netbios.NCBASTAT - ncb.Lana_num = byte_to_int(la_enum.lana[i]) + ncb.Lana_num = la_enum.lana[i] ncb.Callname = b"* " adapter = netbios.ADAPTER_STATUS() ncb.Buffer = adapter From 630ffa3a372874784b9e6f8b68359179b9ec259b Mon Sep 17 00:00:00 2001 From: Avasam Date: Mon, 24 Jul 2023 10:53:01 -0400 Subject: [PATCH 3/4] Fix pycln undecidable cases (#2051) Co-authored-by: Avasam Co-authored-by: Mark Hammond --- Pythonwin/pywin/framework/editor/__init__.py | 3 -- adodbapi/__init__.py | 48 +++++++++++--------- com/win32comext/adsi/__init__.py | 2 +- 3 files changed, 28 insertions(+), 25 deletions(-) diff --git a/Pythonwin/pywin/framework/editor/__init__.py b/Pythonwin/pywin/framework/editor/__init__.py index ce13ece65..16e315818 100644 --- a/Pythonwin/pywin/framework/editor/__init__.py +++ b/Pythonwin/pywin/framework/editor/__init__.py @@ -5,9 +5,6 @@ # This really isnt necessary with Scintilla, and scintilla # is getting so deeply embedded that it was too much work. -import sys - -import win32con import win32ui defaultCharacterFormat = (-402653169, 0, 200, 0, 0, 0, 49, "Courier New") diff --git a/adodbapi/__init__.py b/adodbapi/__init__.py index 0d769e058..428bdf432 100644 --- a/adodbapi/__init__.py +++ b/adodbapi/__init__.py @@ -3,30 +3,36 @@ Copyright (C) 2002 Henrik Ekelund, version 2.1 by Vernon Cole * http://sourceforge.net/projects/adodbapi """ -import sys import time -from .adodbapi import Connection, Cursor, __version__, connect, dateconverter +# Re-exports to keep backward compatibility with existing code +from .adodbapi import ( + Connection as Connection, + Cursor as Cursor, + __version__, + connect as connect, + dateconverter, +) from .apibase import ( - BINARY, - DATETIME, - NUMBER, - ROWID, - STRING, - DatabaseError, - DataError, - Error, - FetchFailedError, - IntegrityError, - InterfaceError, - InternalError, - NotSupportedError, - OperationalError, - ProgrammingError, - Warning, - apilevel, - paramstyle, - threadsafety, + BINARY as BINARY, + DATETIME as DATETIME, + NUMBER as NUMBER, + ROWID as ROWID, + STRING as STRING, + DatabaseError as DatabaseError, + DataError as DataError, + Error as Error, + FetchFailedError as FetchFailedError, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + ProgrammingError as ProgrammingError, + Warning as Warning, + apilevel as apilevel, + paramstyle as paramstyle, + threadsafety as threadsafety, ) diff --git a/com/win32comext/adsi/__init__.py b/com/win32comext/adsi/__init__.py index 69b4c53c3..9ba8d4b53 100644 --- a/com/win32comext/adsi/__init__.py +++ b/com/win32comext/adsi/__init__.py @@ -25,7 +25,7 @@ # interface, as well as via IDispatch. import pythoncom -from .adsi import * +from .adsi import * # nopycln: import # win32comext/adsi/adsi.pyd LCID = 0 From ba9e475904a5c6c55635d1eda145c51627de43f3 Mon Sep 17 00:00:00 2001 From: Avasam Date: Thu, 10 Aug 2023 13:25:52 -0400 Subject: [PATCH 4/4] Cleanup unsupported python code (except for adodbapi) (#1990) --- Pythonwin/pywin/debugger/debugger.py | 9 ++-- Pythonwin/pywin/framework/app.py | 22 +++------ Pythonwin/pywin/framework/mdi_pychecker.py | 2 +- Pythonwin/pywin/framework/scriptutils.py | 7 ++- Pythonwin/pywin/framework/stdin.py | 2 +- Pythonwin/pywin/idle/PyParse.py | 2 +- Pythonwin/pywin/idle/readme.txt | 13 +++--- Pythonwin/pywin/mfc/dialog.py | 5 ++- Pythonwin/pywin/mfc/object.py | 2 +- Pythonwin/pywin/tools/browser.py | 19 ++------ Pythonwin/pywin/tools/hierlist.py | 11 +---- com/win32com/client/__init__.py | 8 ++-- com/win32com/client/build.py | 9 +--- com/win32com/client/combrowse.py | 4 +- com/win32com/client/genpy.py | 15 ++----- com/win32com/client/makepy.py | 10 +---- com/win32com/client/selecttlb.py | 4 +- com/win32com/demos/connect.py | 3 -- com/win32com/demos/excelRTDServer.py | 4 +- com/win32com/demos/iebutton.py | 2 +- com/win32com/demos/ietoolbar.py | 2 +- com/win32com/server/dispatcher.py | 5 --- com/win32com/server/register.py | 2 +- com/win32com/test/testPersist.py | 4 +- com/win32com/test/testPippo.py | 5 +-- com/win32com/test/testPyComTest.py | 42 ++--------------- com/win32com/test/testStreams.py | 2 +- com/win32com/test/testvb.py | 45 +++++++++---------- com/win32com/test/util.py | 4 -- .../axdebug/src/PyIDebugStackFrame.cpp | 2 +- com/win32comext/axscript/client/framework.py | 1 - com/win32comext/axscript/test/leakTest.py | 13 +++--- com/win32comext/axscript/test/testHost.py | 12 ----- com/win32comext/mapi/mapiutil.py | 1 - .../shell/demos/ITransferAdviseSink.py | 1 - .../taskscheduler/test/test_addtask_1.py | 3 +- .../taskscheduler/test/test_addtask_2.py | 4 +- pywin32_postinstall.py | 2 +- setup.py | 39 ++++++++-------- win32/Demos/BackupRead_BackupWrite.py | 1 - win32/Demos/OpenEncryptedFileRaw.py | 1 - win32/Demos/win32clipboardDemo.py | 5 +-- win32/Demos/win32gui_dialog.py | 2 +- win32/Demos/win32gui_menu.py | 5 --- win32/Demos/win32gui_taskbar.py | 5 --- win32/Lib/dbi.py | 27 ----------- win32/Lib/pywintypes.py | 2 +- win32/Lib/sspi.py | 4 +- win32/Lib/win32timezone.py | 10 ++--- win32/Lib/win32traceutil.py | 2 +- win32/Lib/winnt.py | 20 ++------- win32/help/win32net.html | 2 +- win32/scripts/regsetup.py | 2 +- win32/scripts/setup_d.py | 4 +- win32/src/PyHANDLE.cpp | 4 +- win32/test/test_clipboard.py | 2 +- win32/test/test_exceptions.py | 16 ++----- win32/test/test_pywintypes.py | 10 ++--- win32/test/test_sspi.py | 1 - win32/test/test_win32timezone.py | 11 ----- 60 files changed, 139 insertions(+), 339 deletions(-) delete mode 100644 win32/Lib/dbi.py diff --git a/Pythonwin/pywin/debugger/debugger.py b/Pythonwin/pywin/debugger/debugger.py index 3821854f2..320e34ddf 100644 --- a/Pythonwin/pywin/debugger/debugger.py +++ b/Pythonwin/pywin/debugger/debugger.py @@ -695,13 +695,12 @@ def user_exception(self, frame, exc_info): if self.get_option(OPT_STOP_EXCEPTIONS): frame.f_locals["__exception__"] = exc_type, exc_value print("Unhandled exception while debugging...") - # on both py2k and py3k, we may be called with exc_value + # We may be called with exc_value # being the args to the exception, or it may already be # instantiated (IOW, PyErr_Normalize() hasn't been - # called on the args). In py2k this is fine, but in - # py3k, traceback.print_exception fails. So on py3k - # we instantiate an exception instance to print. - if sys.version_info > (3,) and not isinstance(exc_value, BaseException): + # called on the args). traceback.print_exception fails. + # So we instantiate an exception instance to print. + if not isinstance(exc_value, BaseException): # they are args - may be a single item or already a tuple if not isinstance(exc_value, tuple): exc_value = (exc_value,) diff --git a/Pythonwin/pywin/framework/app.py b/Pythonwin/pywin/framework/app.py index b58242307..298a79b4f 100644 --- a/Pythonwin/pywin/framework/app.py +++ b/Pythonwin/pywin/framework/app.py @@ -400,8 +400,8 @@ def OnButHomePage(self, id, code): ) -def Win32RawInput(prompt=None): - "Provide raw_input() for gui apps" +def Win32Input(prompt=None): + "Provide input() for gui apps" # flush stderr/out first. try: sys.stdout.flush() @@ -416,22 +416,10 @@ def Win32RawInput(prompt=None): return ret -def Win32Input(prompt=None): - "Provide input() for gui apps" - return eval(input(prompt)) - - def HookInput(): - try: - raw_input - # must be py2x... - sys.modules["__builtin__"].raw_input = Win32RawInput - sys.modules["__builtin__"].input = Win32Input - except NameError: - # must be py3k - import code - - sys.modules["builtins"].input = Win32RawInput + import code + + sys.modules["builtins"].input = Win32Input def HaveGoodGUI(): diff --git a/Pythonwin/pywin/framework/mdi_pychecker.py b/Pythonwin/pywin/framework/mdi_pychecker.py index db1662b46..06fbcc82b 100644 --- a/Pythonwin/pywin/framework/mdi_pychecker.py +++ b/Pythonwin/pywin/framework/mdi_pychecker.py @@ -17,7 +17,7 @@ ## the PATH. Example pychecker.bat: ## ## REM pychecker.bat -## C:\bin\python.exe C:\PYTHON23\Lib\site-packages\pychecker\checker.py %1 %2 %3 %4 %5 %6 %7 %8 %9 +## C:\bin\python.exe C:\PythonXX\Lib\site-packages\pychecker\checker.py %1 %2 %3 %4 %5 %6 %7 %8 %9 ## ## Adding it as default module in PythonWin: ## diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index 0f4830d42..5bb8544d3 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -89,7 +89,7 @@ def IsOnPythonPath(path): # must check that the command line arg's path is in sys.path for syspath in sys.path: try: - # Python 1.5 and later allows an empty sys.path entry. + # sys.path can have an empty entry. if syspath and win32ui.FullPath(syspath) == path: return 1 except win32ui.error as details: @@ -305,7 +305,7 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): # ignores any encoding decls (bad!). If we use binary mode we get # the raw bytes and Python looks at the encoding (good!) but \r\n # chars stay in place so Python throws a syntax error (bad!). - # So: so the binary thing and manually normalize \r\n. + # So: do the binary thing and manually normalize \r\n. try: f = open(script, "rb") except IOError as exc: @@ -438,8 +438,7 @@ def ImportFile(): newPath = None # note that some packages (*cough* email *cough*) use "lazy importers" # meaning sys.modules can change as a side-effect of looking at - # module.__file__ - so we must take a copy (ie, items() in py2k, - # list(items()) in py3k) + # module.__file__ - so we must take a copy (ie, list(items())) for key, mod in list(sys.modules.items()): if getattr(mod, "__file__", None): fname = mod.__file__ diff --git a/Pythonwin/pywin/framework/stdin.py b/Pythonwin/pywin/framework/stdin.py index 26c8895fd..a9b56e9f1 100644 --- a/Pythonwin/pywin/framework/stdin.py +++ b/Pythonwin/pywin/framework/stdin.py @@ -140,7 +140,7 @@ def readlines(self, *sizehint): """ def fake_input(prompt=None): - """Replacement for raw_input() which pulls lines out of global test_input. + """Replacement for input() which pulls lines out of global test_input. For testing only! """ global test_input diff --git a/Pythonwin/pywin/idle/PyParse.py b/Pythonwin/pywin/idle/PyParse.py index 97629eee5..b11b4744e 100644 --- a/Pythonwin/pywin/idle/PyParse.py +++ b/Pythonwin/pywin/idle/PyParse.py @@ -150,7 +150,7 @@ def set_str(self, str): # no way to tell the differences between output, >>> etc and # user input. Indeed, IDLE's first output line makes the rest # look like it's in an unclosed paren!: - # Python 1.5.2 (#0, Apr 13 1999, ... + # Python X.X.X (#0, Apr 13 1999, ... def find_good_parse_start(self, use_ps1, is_char_in_string=None): str, pos = self.str, None diff --git a/Pythonwin/pywin/idle/readme.txt b/Pythonwin/pywin/idle/readme.txt index 8ded39fc7..9a28195a2 100644 --- a/Pythonwin/pywin/idle/readme.txt +++ b/Pythonwin/pywin/idle/readme.txt @@ -2,15 +2,14 @@ Pythonwin IDLE directory ------------------------ This directory contains IDLE extensions used by -Pythonwin. In ALL cases, the files in this directory that also appear -in the main IDLE directory should be indentical to the latest available -for IDLE. +Pythonwin. The files in this directory that also appear in the main IDLE +directory are intended be indentical to the latest available for IDLE. -Eg, If you have Python 1.5.2 installed, the files in this -directory will be later than the IDLE versions. If you use IDLE from -the CVS sources, then the files should be identical. +If you use IDLE from the CVS sources, then the files should be +identical. If you have a Python version installed that is more recent +than when this release was made, then you may notice differences. Pythonwin will look for IDLE extensions first in this directory, then on the global sys.path. Thus, if you have IDLE installed and run it from the CVS sources, you may remove most of the extensions from this -directory, and the latest CVS version will then be used. +directory, and the latest CVS version will then be used. diff --git a/Pythonwin/pywin/mfc/dialog.py b/Pythonwin/pywin/mfc/dialog.py index 6e528d9b6..280c025aa 100644 --- a/Pythonwin/pywin/mfc/dialog.py +++ b/Pythonwin/pywin/mfc/dialog.py @@ -90,10 +90,11 @@ def items(self): def values(self): return list(self.data.values()) - # XXX - needs py3k work! - def has_key(self, key): + def __contains__(self, key): return key in self.data + has_key = __contains__ + class PrintDialog(Dialog): "Base class for a print dialog" diff --git a/Pythonwin/pywin/mfc/object.py b/Pythonwin/pywin/mfc/object.py index 70138b6ee..063f835f7 100644 --- a/Pythonwin/pywin/mfc/object.py +++ b/Pythonwin/pywin/mfc/object.py @@ -23,7 +23,7 @@ def __getattr__( if o is not None: return getattr(o, attr) # Only raise this error for non "internal" names - - # Python may be calling __len__, __nonzero__, etc, so + # Python may be calling __len__, __bool__, etc, so # we dont want this exception if attr[0] != "_" and attr[-1] != "_": raise win32ui.error("The MFC object has died.") diff --git a/Pythonwin/pywin/tools/browser.py b/Pythonwin/pywin/tools/browser.py index 188993259..6dfe3a24f 100644 --- a/Pythonwin/pywin/tools/browser.py +++ b/Pythonwin/pywin/tools/browser.py @@ -241,21 +241,10 @@ def IsExpandable(self): return 1 def GetSubList(self): - ret = [] - # ret.append( MakeHLI( self.myobject.func_argcount, "Arg Count" )) - try: - ret.append(MakeHLI(self.myobject.func_argdefs, "Arg Defs")) - except AttributeError: - pass - try: - code = self.myobject.__code__ - globs = self.myobject.__globals__ - except AttributeError: - # must be py2.5 or earlier... - code = self.myobject.func_code - globs = self.myobject.func_globals - ret.append(MakeHLI(code, "Code")) - ret.append(MakeHLI(globs, "Globals")) + ret = [ + MakeHLI(self.myobject.__code__, "Code"), + MakeHLI(self.myobject.__globals__, "Globals"), + ] self.InsertDocString(ret) return ret diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index 2ab7f616d..4f27da9a9 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -13,7 +13,6 @@ # choice. However, you should investigate using the tree control directly # to provide maximum flexibility (but with extra work). -import sys import commctrl import win32api @@ -123,12 +122,8 @@ def DeleteAllItems(self): def HierTerm(self): # Dont want notifies as we kill the list. parent = self.notify_parent # GetParentFrame() - if sys.version_info[0] < 3: - parent.HookNotify(None, commctrl.TVN_ITEMEXPANDINGA) - parent.HookNotify(None, commctrl.TVN_SELCHANGEDA) - else: - parent.HookNotify(None, commctrl.TVN_ITEMEXPANDINGW) - parent.HookNotify(None, commctrl.TVN_SELCHANGEDW) + parent.HookNotify(None, commctrl.TVN_ITEMEXPANDINGW) + parent.HookNotify(None, commctrl.TVN_SELCHANGEDW) parent.HookNotify(None, commctrl.NM_DBLCLK) self.DeleteAllItems() @@ -351,11 +346,9 @@ def GetBitmapColumn(self): def GetSelectedBitmapColumn(self): return None # same as other - # for py3k/rich-comp sorting compatibility. def __lt__(self, other): # we want unrelated items to be sortable... return id(self) < id(other) - # for py3k/rich-comp equality compatibility. def __eq__(self, other): return False diff --git a/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index 3ce112046..6e23e7054 100644 --- a/com/win32com/client/__init__.py +++ b/com/win32com/client/__init__.py @@ -623,7 +623,7 @@ def __init__(self, oobj=None): "__int__", "__iter__", "__len__", - "__nonzero__", + "__bool__", ]: if hasattr(dispobj, maybe): setattr(self, maybe, getattr(self, "__maybe" + maybe)) @@ -673,8 +673,8 @@ def __maybe__iter__(self): def __maybe__len__(self): return self.__dict__["_dispobj_"].__len__() - def __maybe__nonzero__(self): - return self.__dict__["_dispobj_"].__nonzero__() + def __maybe__bool__(self): + return self.__dict__["_dispobj_"].__bool__() # A very simple VARIANT class. Only to be used with poorly-implemented COM @@ -682,7 +682,7 @@ def __maybe__nonzero__(self): # is very pickly about the actual variant type (eg, isn't happy with a VT_I4, # which it would get from a Python integer), you can use this to force a # particular VT. -class VARIANT(object): +class VARIANT: def __init__(self, vt, value): self.varianttype = vt self._value = value diff --git a/com/win32com/client/build.py b/com/win32com/client/build.py index dc43aae0a..84dacb566 100644 --- a/com/win32com/client/build.py +++ b/com/win32com/client/build.py @@ -18,7 +18,6 @@ import datetime import string -import sys from keyword import iskeyword import pythoncom @@ -30,8 +29,6 @@ # literals like a quote char and backslashes makes life a little painful to # always render the string perfectly - so just punt and fall-back to a repr() def _makeDocString(s): - if sys.version_info < (3,): - s = s.encode("mbcs") return repr(s) @@ -631,8 +628,7 @@ def _BuildArgList(fdesc, names): while len(names) < numArgs: names.append("arg%d" % (len(names),)) # As per BuildCallList(), avoid huge lines. - # Hack a "\n" at the end of every 5th name - "strides" would be handy - # here but don't exist in 2.2 + # Hack a "\n" at the end of every 5th name for i in range(0, len(names), 5): names[i] = names[i] + "\n\t\t\t" return "," + ", ".join(names) @@ -667,7 +663,7 @@ def MakePublicAttributeName(className, is_global=False): # it would get picked up below className = "NONE" elif iskeyword(className): - # most keywords are lower case (except True, False etc in py3k) + # most keywords are lower case (except True, False, etc) ret = className.capitalize() # but those which aren't get forced upper. if ret == className: @@ -769,7 +765,6 @@ def BuildCallList( defArgVal = defUnnamedArg argName = MakePublicAttributeName(argName) - # insanely long lines with an 'encoding' flag crashes python 2.4.0 # keep 5 args per line # This may still fail if the arg names are insane, but that seems # unlikely. See also _BuildArgList() diff --git a/com/win32com/client/combrowse.py b/com/win32com/client/combrowse.py index be2e7805e..6e1e83624 100644 --- a/com/win32com/client/combrowse.py +++ b/com/win32com/client/combrowse.py @@ -45,8 +45,8 @@ def GetSubList(self): HLIHeadingRegisterdTypeLibs(), ] - def __cmp__(self, other): - return cmp(self.name, other.name) + def __lt__(self, other): + return self.name < other.name class HLICOM(browser.HLIPythonObject): diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index a49481524..c00a77e19 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -107,16 +107,7 @@ def WriteSinkEventMap(obj, stream): # MI is used to join my writable helpers, and the OLE # classes. class WritableItem: - # __cmp__ used for sorting in py2x... - def __cmp__(self, other): - "Compare for sorting" - ret = cmp(self.order, other.order) - if ret == 0 and self.doc: - ret = cmp(self.doc[0], other.doc[0]) - return ret - - # ... but not used in py3k - __lt__ minimum needed there - def __lt__(self, other): # py3k variant + def __lt__(self, other): if self.order == other.order: return self.doc < other.doc return self.order < other.order @@ -747,12 +738,12 @@ def WriteClassBody(self, generator): ) for line in ret: print(line, file=stream) - # Also include a __nonzero__ + # Also include a __bool__ print( "\t#This class has a __len__ - this is needed so 'if object:' always returns TRUE.", file=stream, ) - print("\tdef __nonzero__(self):", file=stream) + print("\tdef __bool__(self):", file=stream) print("\t\treturn True", file=stream) diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index 901c97429..18974305b 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -72,8 +72,6 @@ bForDemandDefault = 0 # Default value of bForDemand - toggle this to change the world - see also gencache.py -error = "makepy.error" - def usage(): sys.stderr.write(usageHelp) @@ -407,7 +405,7 @@ def main(): elif o == "-d": bForDemand = not bForDemand - except (getopt.error, error) as msg: + except getopt.error as msg: sys.stderr.write(str(msg) + "\n") usage() @@ -427,12 +425,8 @@ def main(): path = os.path.dirname(outputName) if path != "" and not os.path.exists(path): os.makedirs(path) - if sys.version_info > (3, 0): - f = open(outputName, "wt", encoding="mbcs") - else: - import codecs # not available in py3k. + f = open(outputName, "wt", encoding="mbcs") - f = codecs.open(outputName, "w", "mbcs") else: f = None diff --git a/com/win32com/client/selecttlb.py b/com/win32com/client/selecttlb.py index bb21a4291..1337bc468 100644 --- a/com/win32com/client/selecttlb.py +++ b/com/win32com/client/selecttlb.py @@ -27,7 +27,7 @@ def __getitem__(self, item): return self.ver_desc raise IndexError("Cant index me!") - def __lt__(self, other): # rich-cmp/py3k-friendly version + def __lt__(self, other): me = ( (self.ver_desc or "").lower(), (self.desc or "").lower(), @@ -42,7 +42,7 @@ def __lt__(self, other): # rich-cmp/py3k-friendly version ) return me < them - def __eq__(self, other): # rich-cmp/py3k-friendly version + def __eq__(self, other): return ( (self.ver_desc or "").lower() == (other.ver_desc or "").lower() and (self.desc or "").lower() == (other.desc or "").lower() diff --git a/com/win32com/demos/connect.py b/com/win32com/demos/connect.py index cb5928b6a..3099214c9 100644 --- a/com/win32com/demos/connect.py +++ b/com/win32com/demos/connect.py @@ -8,7 +8,6 @@ import pythoncom import win32com.server.connect import win32com.server.util -from win32com.server.exception import Exception # This is the IID of the Events interface both Client and Server support. IID_IConnectDemoEvents = pythoncom.MakeIID("{A4988850-49C3-11d0-AE5D-52342E000000}") @@ -50,8 +49,6 @@ def __init__(self): # A client must implement QI, and respond to a query for the Event interface. # In addition, it must provide a COM object (which server.util.wrap) does. def _query_interface_(self, iid): - import win32com.server.util - # Note that this seems like a necessary hack. I am responding to IID_IConnectDemoEvents # but only creating an IDispatch gateway object. if iid == IID_IConnectDemoEvents: diff --git a/com/win32com/demos/excelRTDServer.py b/com/win32com/demos/excelRTDServer.py index c50e1ac78..6eda46953 100644 --- a/com/win32com/demos/excelRTDServer.py +++ b/com/win32com/demos/excelRTDServer.py @@ -69,7 +69,7 @@ ) -class ExcelRTDServer(object): +class ExcelRTDServer: """Base RTDServer class. Provides most of the features needed to implement the IRtdServer interface. @@ -260,7 +260,7 @@ def OnServerTerminate(self): pass -class RTDTopic(object): +class RTDTopic: """Base RTD Topic. Only method required by our RTDServer implementation is GetValue(). The others are more for convenience.""" diff --git a/com/win32com/demos/iebutton.py b/com/win32com/demos/iebutton.py index bc3ce99bf..0feb0e488 100644 --- a/com/win32com/demos/iebutton.py +++ b/com/win32com/demos/iebutton.py @@ -3,7 +3,7 @@ # PyWin32 Internet Explorer Button # # written by Leonard Ritter (paniq@gmx.net) -# and Robert Förtsch (info@robert-foertsch.com) +# and Robert Förtsch (info@robert-foertsch.com) """ diff --git a/com/win32com/demos/ietoolbar.py b/com/win32com/demos/ietoolbar.py index 084db3c1a..b259c406d 100644 --- a/com/win32com/demos/ietoolbar.py +++ b/com/win32com/demos/ietoolbar.py @@ -3,7 +3,7 @@ # PyWin32 Internet Explorer Toolbar # # written by Leonard Ritter (paniq@gmx.net) -# and Robert Förtsch (info@robert-foertsch.com) +# and Robert Förtsch (info@robert-foertsch.com) """ diff --git a/com/win32com/server/dispatcher.py b/com/win32com/server/dispatcher.py index ac9831250..71b91e7a5 100644 --- a/com/win32com/server/dispatcher.py +++ b/com/win32com/server/dispatcher.py @@ -8,8 +8,6 @@ import pythoncom import win32api import win32com - -# from win32com.server.exception import IsCOMServerException from win32com.util import IIDToInterfaceName @@ -243,9 +241,6 @@ class DispatcherWin32dbg(DispatcherBase): """ def __init__(self, policyClass, ob): - # No one uses this, and it just causes py2exe to drag all of - # pythonwin in. - # import pywin.debugger pywin.debugger.brk() print("The DispatcherWin32dbg dispatcher is deprecated!") print("Please let me know if this is a problem.") diff --git a/com/win32com/server/register.py b/com/win32com/server/register.py index ae513c754..6c8922e5a 100644 --- a/com/win32com/server/register.py +++ b/com/win32com/server/register.py @@ -94,7 +94,7 @@ def _cat_registrar(): def _find_localserver_exe(mustfind): - if not sys.platform.startswith("win32"): + if sys.platform != "win32": return sys.executable if pythoncom.__file__.find("_d") < 0: exeBaseName = "pythonw.exe" diff --git a/com/win32com/test/testPersist.py b/com/win32com/test/testPersist.py index a75ec6436..76f7d84c9 100644 --- a/com/win32com/test/testPersist.py +++ b/com/win32com/test/testPersist.py @@ -7,6 +7,7 @@ import win32com.client import win32com.client.dynamic import win32com.server.util +import win32timezone import win32ui from win32com import storagecon from win32com.axcontrol import axcontrol @@ -14,9 +15,6 @@ S_OK = 0 - -import win32timezone - now = win32timezone.now() diff --git a/com/win32com/test/testPippo.py b/com/win32com/test/testPippo.py index a1a762c2c..414483b53 100644 --- a/com/win32com/test/testPippo.py +++ b/com/win32com/test/testPippo.py @@ -52,9 +52,8 @@ def testNumpyArrays(self): def testByteArrays(self): if "bytes" in dir(__builtins__): - # Use eval to avoid compilation error in Python 2. - self._testArray(eval("b'abcdef'")) - self._testArray(eval("bytearray(b'abcdef')")) + self._testArray(b"abcdef") + self._testArray(bytearray(b"abcdef")) def _testArray(self, inArray): outArray = self.object.Method3(inArray) diff --git a/com/win32com/test/testPyComTest.py b/com/win32com/test/testPyComTest.py index 59b601bc6..c48490aef 100644 --- a/com/win32com/test/testPyComTest.py +++ b/com/win32com/test/testPyComTest.py @@ -17,7 +17,7 @@ import win32timezone import winerror from win32com.client import VARIANT, CastTo, DispatchBaseClass, constants -from win32com.test.util import CheckClean, RegisterPythonServer +from win32com.test.util import RegisterPythonServer importMsg = "**** PyCOMTest is not installed ***\n PyCOMTest is a Python test specific COM client and server.\n It is likely this server is not installed on this machine\n To install the server, you must get the win32com sources\n and build it using MS Visual C++" @@ -126,38 +126,6 @@ def _DumpFireds(self): progress("ID %d fired %d times" % (firedId, no)) -# A simple handler class that derives from object (ie, a "new style class") - -# only relevant for Python 2.x (ie, the 2 classes should be identical in 3.x) -class NewStyleRandomEventHandler(object): - def _Init(self): - self.fireds = {} - - def OnFire(self, no): - try: - self.fireds[no] = self.fireds[no] + 1 - except KeyError: - self.fireds[no] = 0 - - def OnFireWithNamedParams(self, no, a_bool, out1, out2): - # This test exists mainly to help with an old bug, where named - # params would come in reverse. - Missing = pythoncom.Missing - if no is not Missing: - # We know our impl called 'OnFire' with the same ID - assert no in self.fireds - assert no + 1 == out1, "expecting 'out1' param to be ID+1" - assert no + 2 == out2, "expecting 'out2' param to be ID+2" - # The middle must be a boolean. - assert a_bool is Missing or isinstance(a_bool, bool), "middle param not a bool" - return out1 + 2, out2 + 2 - - def _DumpFireds(self): - if not self.fireds: - print("ERROR: Nothing was received!") - for firedId, no in self.fireds.items(): - progress("ID %d fired %d times" % (firedId, no)) - - # Test everything which can be tested using both the "dynamic" and "generated" # COM objects (or when there are very subtle differences) def TestCommon(o, is_generated): @@ -228,9 +196,9 @@ def TestCommon(o, is_generated): if o.GetSetUnsignedLong(-1) != 0xFFFFFFFF: raise error("unsigned -1 failed") - # We want to explicitly test > 32 bits. py3k has no 'maxint' and + # We want to explicitly test > 32 bits. # 'maxsize+1' is no good on 64bit platforms as its 65 bits! - big = 2147483647 # sys.maxint on py2k + big = 2147483647 for l in big, big + 1, 1 << 65: check_get_set(o.GetSetVariant, l) @@ -532,13 +500,9 @@ def TestGenerated(): progress("Testing connection points") o2 = win32com.client.DispatchWithEvents(o, RandomEventHandler) TestEvents(o2, o2) - o2 = win32com.client.DispatchWithEvents(o, NewStyleRandomEventHandler) - TestEvents(o2, o2) # and a plain "WithEvents". handler = win32com.client.WithEvents(o, RandomEventHandler) TestEvents(o, handler) - handler = win32com.client.WithEvents(o, NewStyleRandomEventHandler) - TestEvents(o, handler) progress("Finished generated .py test.") diff --git a/com/win32com/test/testStreams.py b/com/win32com/test/testStreams.py index da0329d5b..b43da524f 100644 --- a/com/win32com/test/testStreams.py +++ b/com/win32com/test/testStreams.py @@ -127,7 +127,7 @@ def testit(self): def testseek(self): s = Stream(b"yo") s = win32com.server.util.wrap(s, pythoncom.IID_IStream) - # we used to die in py3k passing a value > 32bits + # we used to die passing a value > 32bits s.Seek(0x100000000, pythoncom.STREAM_SEEK_SET) def testerrors(self): diff --git a/com/win32com/test/testvb.py b/com/win32com/test/testvb.py index 46d0f08f0..c82b4e73f 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -3,7 +3,6 @@ # This requires the PythonCOM VB Test Harness. # -import sys import traceback import pythoncom @@ -11,7 +10,7 @@ import win32com.client.dynamic import win32com.client.gencache import winerror -from win32com.server.util import NewCollection, wrap +from win32com.server.util import wrap from win32com.test import util # for debugging @@ -423,17 +422,16 @@ def TestStructs(vbtest): # Now do some object equality tests. assert s == s assert s is not None - if sys.version_info > (3, 0): - try: - s < None - raise error("Expected type error") - except TypeError: - pass - try: - None < s - raise error("Expected type error") - except TypeError: - pass + try: + s < None + raise error("Expected type error") + except TypeError: + pass + try: + None < s + raise error("Expected type error") + except TypeError: + pass assert s != s.sub_val import copy @@ -527,17 +525,16 @@ def TestObjectSemantics(ob): assert None != ob._oleobj_ assert ob is not None assert None != ob - if sys.version_info > (3, 0): - try: - ob < None - raise error("Expected type error") - except TypeError: - pass - try: - None < ob - raise error("Expected type error") - except TypeError: - pass + try: + ob < None + raise error("Expected type error") + except TypeError: + pass + try: + None < ob + raise error("Expected type error") + except TypeError: + pass assert ob._oleobj_.QueryInterface(pythoncom.IID_IUnknown) == ob._oleobj_ assert not ob._oleobj_.QueryInterface(pythoncom.IID_IUnknown) != ob._oleobj_ diff --git a/com/win32com/test/util.py b/com/win32com/test/util.py index 691be8519..d36a0da91 100644 --- a/com/win32com/test/util.py +++ b/com/win32com/test/util.py @@ -19,10 +19,6 @@ def CheckClean(): # Ensure no lingering exceptions - Python should have zero outstanding # COM objects - try: - sys.exc_clear() - except AttributeError: - pass # py3k c = _GetInterfaceCount() if c: print("Warning - %d com interface objects still alive" % c) diff --git a/com/win32comext/axdebug/src/PyIDebugStackFrame.cpp b/com/win32comext/axdebug/src/PyIDebugStackFrame.cpp index f715d2d05..c119e29a0 100644 --- a/com/win32comext/axdebug/src/PyIDebugStackFrame.cpp +++ b/com/win32comext/axdebug/src/PyIDebugStackFrame.cpp @@ -71,7 +71,7 @@ PyObject *PyIDebugStackFrame::GetLanguageString(PyObject *self, PyObject *args) BSTR pbstrDescription; BOOL flong; // @pyparm int|fLong||If False, just the language name should be provided, eg, "Python". If True a full product - // description may be provided (eg, "Python 1.4 ActiveX Debugging Host") + // description may be provided (eg, "Python X.X ActiveX Debugging Host") if (!PyArg_ParseTuple(args, "i:GetLanguageString", &flong)) return NULL; PY_INTERFACE_PRECALL; diff --git a/com/win32comext/axscript/client/framework.py b/com/win32comext/axscript/client/framework.py index 7203e4ef3..85021c448 100644 --- a/com/win32comext/axscript/client/framework.py +++ b/com/win32comext/axscript/client/framework.py @@ -1057,7 +1057,6 @@ def ChangeScriptState(self, state): self.scriptSite.OnStateChange(state) except pythoncom.com_error as xxx_todo_changeme: (hr, desc, exc, arg) = xxx_todo_changeme.args - # Ignore all errors here - E_NOTIMPL likely from scriptlets. finally: self.EnableInterrupts() diff --git a/com/win32comext/axscript/test/leakTest.py b/com/win32comext/axscript/test/leakTest.py index d8ccac57b..36bd8cf2b 100644 --- a/com/win32comext/axscript/test/leakTest.py +++ b/com/win32comext/axscript/test/leakTest.py @@ -80,7 +80,7 @@ def NotifyDoneIt(self, interface, arg): sub hello(arg1) test.echo arg1 end sub - + sub testcollection test.verbose = 1 for each item in test.collection @@ -88,16 +88,15 @@ def NotifyDoneIt(self, interface, arg): next end sub """ -if sys.version_info < (3,): - PyScript = """print "PyScript is being parsed..."\n""" -else: - PyScript = """print("PyScript is being parsed...")\n""" -PyScript += """\ + +PyScript = """\ +print("PyScript is being parsed...")\n + prop = "Property Value" def hello(arg1): test.echo(arg1) pass - + def testcollection(): test.verbose = 1 # test.collection[1] = "New one" diff --git a/com/win32comext/axscript/test/testHost.py b/com/win32comext/axscript/test/testHost.py index 8ef8bcc09..466bdb3ac 100644 --- a/com/win32comext/axscript/test/testHost.py +++ b/com/win32comext/axscript/test/testHost.py @@ -135,14 +135,6 @@ def testcollection(): pass """ -# XXX - needs py3k work! Throwing a bytes string with an extended char -# doesn't make much sense, but py2x allows it. What it gets upset with -# is a real unicode arg - which is the only thing py3k allows! -PyScript_Exc = """\ -def hello(arg1): - raise RuntimeError("exc with extended \xa9har") -""" - ErrScript = """\ bad code for everyone! """ @@ -248,10 +240,6 @@ def testPythonUnicodeError(self): def testVBExceptions(self): self.assertRaises(pythoncom.com_error, self._TestEngine, "VBScript", ErrScript) - def testPythonExceptions(self): - expected = "RuntimeError: exc with extended \xa9har" - self._TestEngine("Python", PyScript_Exc, expected) - if __name__ == "__main__": unittest.main() diff --git a/com/win32comext/mapi/mapiutil.py b/com/win32comext/mapi/mapiutil.py index b0f20dc88..03d2a6398 100644 --- a/com/win32comext/mapi/mapiutil.py +++ b/com/win32comext/mapi/mapiutil.py @@ -1,5 +1,4 @@ # General utilities for MAPI and MAPI objects. -# We used to use these old names from the 'types' module... import pythoncom from pywintypes import TimeType diff --git a/com/win32comext/shell/demos/ITransferAdviseSink.py b/com/win32comext/shell/demos/ITransferAdviseSink.py index fd00ca15f..fc766fb0b 100644 --- a/com/win32comext/shell/demos/ITransferAdviseSink.py +++ b/com/win32comext/shell/demos/ITransferAdviseSink.py @@ -8,7 +8,6 @@ (k, v) for k, v in list(shellcon.__dict__.items()) if k.startswith("TSF_") ) - TRANSFER_ADVISE_STATES = {} for k, v in list(shellcon.__dict__.items()): if k.startswith("TS_"): diff --git a/com/win32comext/taskscheduler/test/test_addtask_1.py b/com/win32comext/taskscheduler/test/test_addtask_1.py index 29c9e08d2..284e3511e 100644 --- a/com/win32comext/taskscheduler/test/test_addtask_1.py +++ b/com/win32comext/taskscheduler/test/test_addtask_1.py @@ -33,12 +33,11 @@ ) new_task.SetIdleWait(1, 10000) new_task.SetComment("test task with idle trigger") -new_task.SetApplicationName("c:\\python23\\python.exe") +new_task.SetApplicationName("py.exe") new_task.SetPriority(taskscheduler.REALTIME_PRIORITY_CLASS) new_task.SetParameters( "-c\"import win32ui,time;win32ui.MessageBox('why aint you doing no work ?');\"" ) -new_task.SetWorkingDirectory("c:\\python23") new_task.SetCreator("test_addtask_1.py") new_task.SetAccountInformation(win32api.GetUserName(), None) ## None is only valid for local system acct or if Flags contain TASK_FLAG_RUN_ONLY_IF_LOGGED_ON diff --git a/com/win32comext/taskscheduler/test/test_addtask_2.py b/com/win32comext/taskscheduler/test/test_addtask_2.py index 4663bea46..5c2f7c8dd 100644 --- a/com/win32comext/taskscheduler/test/test_addtask_2.py +++ b/com/win32comext/taskscheduler/test/test_addtask_2.py @@ -20,10 +20,10 @@ t = ts.NewWorkItem(task_name) t.SetComment("Test a task running as local system acct") -t.SetApplicationName("c:\\python23\\python.exe") +t.SetApplicationName("c:\\Python37\\python.exe") t.SetPriority(taskscheduler.REALTIME_PRIORITY_CLASS) t.SetParameters("test_localsystem.py") -t.SetWorkingDirectory("c:\\python23") +t.SetWorkingDirectory("c:\\Python37") t.SetCreator("test_addtask_2.py") t.SetMaxRunTime(20000) # milliseconds t.SetFlags(taskscheduler.TASK_FLAG_DELETE_WHEN_DONE) diff --git a/pywin32_postinstall.py b/pywin32_postinstall.py index 147f0cde7..5b6a6da74 100644 --- a/pywin32_postinstall.py +++ b/pywin32_postinstall.py @@ -69,7 +69,7 @@ def flush(self): try: # When this script is run from inside the bdist_wininst installer, # file_created() and directory_created() are additional builtin - # functions which write lines to Python23\pywin32-install.log. This is + # functions which write lines to PythonXX\pywin32-install.log. This is # a list of actions for the uninstaller, the format is inspired by what # the Wise installer also creates. file_created diff --git a/setup.py b/setup.py index 82fd384a6..ecaa7a692 100644 --- a/setup.py +++ b/setup.py @@ -2410,23 +2410,22 @@ def maybe_fixup_exes(): if "install" in dist.command_obj: # just to be purdy what_string += "/installed" # Print the list of extension modules we skipped building. - if "build_ext" in dist.command_obj: - excluded_extensions = dist.command_obj["build_ext"].excluded_extensions - if excluded_extensions: - skip_whitelist = {"exchdapi", "exchange", "axdebug", "winxpgui"} - skipped_ex = [] - print("*** NOTE: The following extensions were NOT %s:" % what_string) - for ext, why in excluded_extensions: - print(" %s: %s" % (ext.name, why)) - if ext.name not in skip_whitelist: - skipped_ex.append(ext.name) - print("For more details on installing the correct libraries and headers,") - print("please execute this script with no arguments (or see the docstring)") - if skipped_ex: - print( - "*** Non-zero exit status. Missing for complete release build: %s" - % skipped_ex - ) - sys.exit(1000 + len(skipped_ex)) - else: - print("All extension modules %s OK" % (what_string,)) + excluded_extensions = dist.command_obj["build_ext"].excluded_extensions + if excluded_extensions: + skip_whitelist = {"exchdapi", "exchange", "axdebug", "winxpgui"} + skipped_ex = [] + print("*** NOTE: The following extensions were NOT %s:" % what_string) + for ext, why in excluded_extensions: + print(" %s: %s" % (ext.name, why)) + if ext.name not in skip_whitelist: + skipped_ex.append(ext.name) + print("For more details on installing the correct libraries and headers,") + print("please execute this script with no arguments (or see the docstring)") + if skipped_ex: + print( + "*** Non-zero exit status. Missing for complete release build: %s" + % skipped_ex + ) + sys.exit(1000 + len(skipped_ex)) + else: + print("All extension modules %s OK" % (what_string,)) diff --git a/win32/Demos/BackupRead_BackupWrite.py b/win32/Demos/BackupRead_BackupWrite.py index 02aae9103..76ce996b1 100644 --- a/win32/Demos/BackupRead_BackupWrite.py +++ b/win32/Demos/BackupRead_BackupWrite.py @@ -1,6 +1,5 @@ ## demonstrates using BackupRead and BackupWrite to copy all of a file's data streams - import ntsecuritycon import pythoncom import pywintypes diff --git a/win32/Demos/OpenEncryptedFileRaw.py b/win32/Demos/OpenEncryptedFileRaw.py index aa0f2a7c1..c9e2d54d8 100644 --- a/win32/Demos/OpenEncryptedFileRaw.py +++ b/win32/Demos/OpenEncryptedFileRaw.py @@ -9,7 +9,6 @@ def ReadCallback(input_buffer, data, buflen): fnamein, fnameout, f = data ## print fnamein, fnameout, buflen f.write(input_buffer) - ## python 2.3 throws an error if return value is a plain int return winerror.ERROR_SUCCESS diff --git a/win32/Demos/win32clipboardDemo.py b/win32/Demos/win32clipboardDemo.py index c65f54664..5794be6ff 100644 --- a/win32/Demos/win32clipboardDemo.py +++ b/win32/Demos/win32clipboardDemo.py @@ -1,7 +1,6 @@ # win32clipboardDemo.py # # Demo/test of the win32clipboard module. - import win32con from win32clipboard import * @@ -115,8 +114,8 @@ class Foo: def __init__(self, **kw): self.__dict__.update(kw) - def __cmp__(self, other): - return cmp(self.__dict__, other.__dict__) + def __lt__(self, other): + return self.__dict__ < other.__dict__ def __eq__(self, other): return self.__dict__ == other.__dict__ diff --git a/win32/Demos/win32gui_dialog.py b/win32/Demos/win32gui_dialog.py index e3b89ba9d..c4086563b 100644 --- a/win32/Demos/win32gui_dialog.py +++ b/win32/Demos/win32gui_dialog.py @@ -146,7 +146,7 @@ def _RegisterWndClass(self): wc.cbWndExtra = win32con.DLGWINDOWEXTRA + struct.calcsize("Pi") icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE - ## py.ico went away in python 2.5, load from executable instead + ## load icon from executable this_app = win32api.GetModuleHandle(None) try: wc.hIcon = win32gui.LoadIcon(this_app, 1) ## python.exe and pythonw.exe diff --git a/win32/Demos/win32gui_menu.py b/win32/Demos/win32gui_menu.py index c462b0622..38c4827eb 100644 --- a/win32/Demos/win32gui_menu.py +++ b/win32/Demos/win32gui_menu.py @@ -60,11 +60,6 @@ def __init__(self): ) UpdateWindow(self.hwnd) iconPathName = os.path.abspath(os.path.join(sys.prefix, "pyc.ico")) - # py2.5 includes the .ico files in the DLLs dir for some reason. - if not os.path.isfile(iconPathName): - iconPathName = os.path.abspath( - os.path.join(os.path.split(sys.executable)[0], "DLLs", "pyc.ico") - ) if not os.path.isfile(iconPathName): # Look in the source tree. iconPathName = os.path.abspath( diff --git a/win32/Demos/win32gui_taskbar.py b/win32/Demos/win32gui_taskbar.py index 84d642a9c..eca439baa 100644 --- a/win32/Demos/win32gui_taskbar.py +++ b/win32/Demos/win32gui_taskbar.py @@ -58,11 +58,6 @@ def _DoCreateIcons(self): iconPathName = os.path.abspath( os.path.join(os.path.split(sys.executable)[0], "pyc.ico") ) - if not os.path.isfile(iconPathName): - # Look in DLLs dir, a-la py 2.5 - iconPathName = os.path.abspath( - os.path.join(os.path.split(sys.executable)[0], "DLLs", "pyc.ico") - ) if not os.path.isfile(iconPathName): # Look in the source tree. iconPathName = os.path.abspath( diff --git a/win32/Lib/dbi.py b/win32/Lib/dbi.py deleted file mode 100644 index c33d6721e..000000000 --- a/win32/Lib/dbi.py +++ /dev/null @@ -1,27 +0,0 @@ -""" -Skeleton replacement for removed dbi module. -Use of objects created by this module should be replaced with native Python objects. -Dates are now returned as datetime.datetime objects, but will still accept PyTime -objects also. -Raw data for binary fields should be passed as buffer objects for Python 2.x, -and memoryview objects in Py3k. -""" - -import warnings - -warnings.warn( - "dbi module is obsolete, code should now use native python datetime and buffer/memoryview objects", - DeprecationWarning, -) - -import datetime - -dbDate = dbiDate = datetime.datetime - -try: - dbRaw = dbiRaw = buffer -except NameError: - dbRaw = dbiRaw = memoryview - -# type names are still exported by odbc module -from odbc import * diff --git a/win32/Lib/pywintypes.py b/win32/Lib/pywintypes.py index 115c4f82f..631e7db88 100644 --- a/win32/Lib/pywintypes.py +++ b/win32/Lib/pywintypes.py @@ -31,7 +31,7 @@ def __import_pywin32_system_module__(modname, globs): suffix, ) if hasattr(sys, "frozen"): - # If we are running from a frozen program (py2exe, McMillan, freeze) + # If we are running from a frozen program (py2exe, McMillan, freeze, PyInstaller) # then we try and load the DLL from our sys.path # XXX - This path may also benefit from _win32sysloader? However, # MarkH has never seen the DLL load problem with py2exe programs... diff --git a/win32/Lib/sspi.py b/win32/Lib/sspi.py index 855a4c35b..b10f63dbc 100644 --- a/win32/Lib/sspi.py +++ b/win32/Lib/sspi.py @@ -19,7 +19,7 @@ error = win32security.error -class _BaseAuth(object): +class _BaseAuth: def __init__(self): self.reset() @@ -384,7 +384,7 @@ def authorize(self, sec_buffer_in): print("Initiator name from the service side:", sspiserver.initiator_name) print("Service name from the client side: ", sspiclient.service_name) - data = b"hello" # py3k-friendly + data = b"hello" # Simple signature, not compatible with GSSAPI. sig = sspiclient.sign(data) diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index fb0b36b54..b65dabdfe 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -248,7 +248,7 @@ # A couple of objects for working with objects as if they were native C-type # structures. -class _SimpleStruct(object): +class _SimpleStruct: _fields_ = None # must be overridden by subclasses def __init__(self, *args, **kw): @@ -678,8 +678,8 @@ def GetDSTEndTime(self, year): "Given a year, determines the time when daylight savings ends." return self.getWinInfo(year).locate_standard_start(year) - def __cmp__(self, other): - return cmp(self.__dict__, other.__dict__) + def __le__(self, other): + return self.__dict__ < other.__dict__ def __eq__(self, other): return self.__dict__ == other.__dict__ @@ -874,7 +874,7 @@ def GetTZCapabilities(): return locals() -class DLLHandleCache(object): +class DLLHandleCache: def __init__(self): self.__cache = {} @@ -914,7 +914,7 @@ class RangeMap(dict): the sorted list of keys. One may supply keyword parameters to be passed to the sort function used - to sort keys (i.e. cmp [python 2 only], keys, reverse) as sort_params. + to sort keys (i.e. keys, reverse) as sort_params. Let's create a map that maps 1-3 -> 'a', 4-6 -> 'b' >>> r = RangeMap({3: 'a', 6: 'b'}) # boy, that was easy diff --git a/win32/Lib/win32traceutil.py b/win32/Lib/win32traceutil.py index 0eb38423e..87f4ee987 100644 --- a/win32/Lib/win32traceutil.py +++ b/win32/Lib/win32traceutil.py @@ -11,7 +11,7 @@ # # then, switch to a DOS prompt, and type: # C:>python.exe -# Python 1.4 etc... +# Python X.X.X (#0, Apr 13 1999, ... # >>> import win32traceutil # Redirecting output to win32trace remote collector # >>> print "Hello" diff --git a/win32/Lib/winnt.py b/win32/Lib/winnt.py index e997527c9..a88627e0f 100644 --- a/win32/Lib/winnt.py +++ b/win32/Lib/winnt.py @@ -161,34 +161,22 @@ def PRIMARYLANGID(lgid): - return (WORD)(lgid) & 1023 + return (lgid) & 1023 def SUBLANGID(lgid): - return (WORD)(lgid) >> 10 + return (lgid) >> 10 NLS_VALID_LOCALE_MASK = 1048575 def LANGIDFROMLCID(lcid): - return (WORD)(lcid) + return lcid def SORTIDFROMLCID(lcid): - return (WORD)((((DWORD)(lcid)) & NLS_VALID_LOCALE_MASK) >> 16) - - -def UNREFERENCED_PARAMETER(P): - return - - -def DBG_UNREFERENCED_PARAMETER(P): - return - - -def DBG_UNREFERENCED_LOCAL_VARIABLE(V): - return + return (((lcid)) & NLS_VALID_LOCALE_MASK) >> 16 MAXIMUM_WAIT_OBJECTS = 64 diff --git a/win32/help/win32net.html b/win32/help/win32net.html index 0ec994900..6ad7ecd2f 100644 --- a/win32/help/win32net.html +++ b/win32/help/win32net.html @@ -70,7 +70,7 @@

Introduction

win32net called win32netcon that houses all of the constants needed by the win32net modules.

-Because of unicode support in python2.0, some of the string handling +Because of unicode support in Python 2.0, some of the string handling done w/the examples are no longer necessary. Before one needed to convert PyUnicode to a regular python string, before you could use string functions with it. The examples will work w/both versions of diff --git a/win32/scripts/regsetup.py b/win32/scripts/regsetup.py index f04dbda76..cf8c5e980 100644 --- a/win32/scripts/regsetup.py +++ b/win32/scripts/regsetup.py @@ -504,7 +504,7 @@ def RegisterShellInfo(searchPaths): "regsetup c:\\wierd\\spot\\1 c:\\wierd\\spot\\2" Attempts to setup the core Python. Looks in some standard places, as well as the 2 wierd spots to locate the core Python files (eg, Python.exe, -python14.dll, the standard library and Win32 Extensions. +pythonXX.dll, the standard library and Win32 Extensions. "regsetup -a myappname . .\subdir" Registers a new Pythonpath entry named myappname, with "C:\\I\\AM\\HERE" and diff --git a/win32/scripts/setup_d.py b/win32/scripts/setup_d.py index babd83596..8d009dfa5 100644 --- a/win32/scripts/setup_d.py +++ b/win32/scripts/setup_d.py @@ -1,4 +1,4 @@ -# Install and register pythonxx_d.dll, pywintypesxx_d.dll and pythoncomxx_d.dll +# Install and register pythonXX_d.dll, pywintypesxx_d.dll and pythoncomxx_d.dll # # Assumes the _d files can be found in the same directory as this script # or in the cwd. @@ -14,7 +14,7 @@ def usage_and_die(rc): print() print("This script is designed to copy and register the Python debug") - print("binaries. It looks for pythonxx_d.dll, pythoncomxx_d.dll etc,") + print("binaries. It looks for pythonXX_d.dll, pythoncomxx_d.dll etc,") print("and installs them to work correctly with Python debug builds.") print() print("You will generally find this script in the. zip file that") diff --git a/win32/src/PyHANDLE.cpp b/win32/src/PyHANDLE.cpp index dd2290aa4..4fdad48f0 100644 --- a/win32/src/PyHANDLE.cpp +++ b/win32/src/PyHANDLE.cpp @@ -120,7 +120,7 @@ static PyNumberMethods PyHANDLE_NumberMethods = { PyHANDLE::unaryFailureFunc, /* nb_negative */ PyHANDLE::unaryFailureFunc, /* nb_positive */ PyHANDLE::unaryFailureFunc, /* nb_absolute */ - // @pymeth __nonzero__|Used for detecting true/false. + // @pymeth __bool__|Used for detecting true/false. PyHANDLE::nonzeroFunc, /* is nb_bool in Python 3.0 */ PyHANDLE::unaryFailureFunc, /* nb_invert */ PyHANDLE::binaryFailureFunc, /* nb_lshift */ @@ -234,7 +234,7 @@ BOOL PyHANDLE::Close(void) return rc; } -// @pymethod |PyHANDLE|__nonzero__|Used for detecting true/false. +// @pymethod |PyHANDLE|__bool__|Used for detecting true/false. // @rdesc The result is 1 if the attached handle is non zero, else 0. /*static*/ int PyHANDLE::nonzeroFunc(PyObject *ob) { return ((PyHANDLE *)ob)->m_handle != 0; } diff --git a/win32/test/test_clipboard.py b/win32/test/test_clipboard.py index 820dd1816..8f74e8575 100644 --- a/win32/test/test_clipboard.py +++ b/win32/test/test_clipboard.py @@ -14,7 +14,7 @@ class CrashingTestCase(unittest.TestCase): def test_722082(self): - class crasher(object): + class crasher: pass obj = crasher() diff --git a/win32/test/test_exceptions.py b/win32/test/test_exceptions.py index 331011073..2944da364 100644 --- a/win32/test/test_exceptions.py +++ b/win32/test/test_exceptions.py @@ -1,5 +1,4 @@ """Test pywin32's error semantics""" -import sys import unittest import pythoncom @@ -11,10 +10,7 @@ class TestBase(unittest.TestCase): def _testExceptionIndex(self, exc, index, expected): - # check the exception itself can be indexed if not py3k - if sys.version_info < (3,): - self.assertEqual(exc[index], expected) - # and that exception.args can is the same. + # Check that exception.args is the same. self.assertEqual(exc.args[index], expected) @@ -66,10 +62,7 @@ def testAsTuple(self): err_msg = win32api.FormatMessage(winerror.ERROR_INVALID_HANDLE).rstrip() # early on the result actually *was* a tuple - it must be able to be one err_tuple = (winerror.ERROR_INVALID_HANDLE, "CloseHandle", err_msg) - if sys.version_info < (3,): - self.assertEqual(tuple(exc), err_tuple) - else: - self.assertEqual(exc.args, err_tuple) + self.assertEqual(exc.args, err_tuple) def testClassName(self): exc = self._getInvalidHandleException() @@ -159,10 +152,7 @@ def testAsTuple(self): err_msg = win32api.FormatMessage(winerror.STG_E_INVALIDFLAG).rstrip() # early on the result actually *was* a tuple - it must be able to be one err_tuple = (winerror.STG_E_INVALIDFLAG, err_msg, None, None) - if sys.version_info < (3,): - self.assertEqual(tuple(exc), err_tuple) - else: - self.assertEqual(exc.args, err_tuple) + self.assertEqual(exc.args, err_tuple) def testClassName(self): exc = self._getException() diff --git a/win32/test/test_pywintypes.py b/win32/test/test_pywintypes.py index 35962be32..0a932fcd3 100644 --- a/win32/test/test_pywintypes.py +++ b/win32/test/test_pywintypes.py @@ -1,6 +1,5 @@ import datetime import operator -import sys import time import unittest @@ -96,11 +95,10 @@ def testGUIDRichCmp(self): self.assertFalse(None == s) self.assertTrue(s is not None) self.assertTrue(None != s) - if sys.version_info > (3, 0): - self.assertRaises(TypeError, operator.gt, None, s) - self.assertRaises(TypeError, operator.gt, s, None) - self.assertRaises(TypeError, operator.lt, None, s) - self.assertRaises(TypeError, operator.lt, s, None) + self.assertRaises(TypeError, operator.gt, None, s) + self.assertRaises(TypeError, operator.gt, s, None) + self.assertRaises(TypeError, operator.lt, None, s) + self.assertRaises(TypeError, operator.lt, s, None) def testGUIDInDict(self): s = "{00020400-0000-0000-C000-000000000046}" diff --git a/win32/test/test_sspi.py b/win32/test/test_sspi.py index 63003b0bc..a9db878e9 100644 --- a/win32/test/test_sspi.py +++ b/win32/test/test_sspi.py @@ -206,7 +206,6 @@ def testSecBufferRepr(self): r"PySecBuffer\(cbBuffer: 0 \| BufferType: 2 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", repr(buffer1), ) - "PySecBuffer(cbBuffer: 0 | BufferType: 2 | pvBuffer: 0x000001B8CC6D8020)" desc.append(buffer1) assert re.match( diff --git a/win32/test/test_win32timezone.py b/win32/test/test_win32timezone.py index 6dba51edc..4f77d437b 100644 --- a/win32/test/test_win32timezone.py +++ b/win32/test/test_win32timezone.py @@ -1,7 +1,6 @@ # Test module for win32timezone import doctest -import sys import unittest import win32timezone @@ -9,16 +8,6 @@ class Win32TimeZoneTest(unittest.TestCase): def testWin32TZ(self): - # On 3.7 and later, the repr() for datetime objects changed to use kwargs - eg, - # eg, `datetime.timedelta(0, 10800)` is now `datetime.timedelta(seconds=10800)`. - # So we just skip the tests on 3.5 and 3.6 - if sys.version_info < (3, 7): - from pywin32_testutil import TestSkipped - - raise TestSkipped( - "The repr() for datetime objects makes this test fail in 3.5 and 3.6" - ) - failed, total = doctest.testmod(win32timezone, verbose=False) self.assertFalse(failed)