diff --git a/AutoDuck/py2d.py b/AutoDuck/py2d.py index ce74e9c95c..7b3f641efe 100644 --- a/AutoDuck/py2d.py +++ b/AutoDuck/py2d.py @@ -106,11 +106,11 @@ def build_module(fp, mod_name): continue if hasattr(ob, "__module__") and ob.__module__ != mod_name: continue - if type(ob) in (type, type): + if type(ob) == type: classes.append(BuildInfo(name, ob)) - elif type(ob) == types.FunctionType: + elif isinstance(ob, types.FunctionType): functions.append(BuildInfo(name, ob)) - elif name.upper() == name and type(ob) in (int, str): + elif name.upper() == name and isinstance(ob, (int, str)): constants.append((name, ob)) info = BuildInfo(mod_name, mod) Print("// @module %s|%s" % (mod_name, format_desc(info.desc)), file=fp) @@ -169,7 +169,7 @@ def build_module(fp, mod_name): for name, val in constants: desc = "%s = %r" % (name, val) - if type(val) in (int, int): + if isinstance(val, int): desc += " (0x%x)" % (val,) Print("// @const %s|%s|%s" % (mod_name, name, desc), file=fp) diff --git a/Pythonwin/pywin/Demos/dlgtest.py b/Pythonwin/pywin/Demos/dlgtest.py index 8dcb0e5efa..acef880176 100644 --- a/Pythonwin/pywin/Demos/dlgtest.py +++ b/Pythonwin/pywin/Demos/dlgtest.py @@ -51,7 +51,7 @@ def OnNotify(self, controlid, code): # Simply increment the value in the text box. def KillFocus(self, msg): self.counter = self.counter + 1 - if self.edit != None: + if self.edit is not None: self.edit.SetWindowText(str(self.counter)) # Called when the dialog box is terminating... diff --git a/Pythonwin/pywin/debugger/__init__.py b/Pythonwin/pywin/debugger/__init__.py index 5f41960d36..31bb76b59c 100644 --- a/Pythonwin/pywin/debugger/__init__.py +++ b/Pythonwin/pywin/debugger/__init__.py @@ -123,7 +123,7 @@ def post_mortem(t=None): # No idea why I need to settrace to None - it should have been reset by now? sys.settrace(None) p.reset() - while t.tb_next != None: + while t.tb_next is not None: t = t.tb_next p.bAtPostMortem = 1 p.prep_run(None) diff --git a/Pythonwin/pywin/debugger/debugger.py b/Pythonwin/pywin/debugger/debugger.py index 4acf9bc4d2..7f21840513 100644 --- a/Pythonwin/pywin/debugger/debugger.py +++ b/Pythonwin/pywin/debugger/debugger.py @@ -751,7 +751,7 @@ def run(self, cmd, globals=None, locals=None, start_stepping=1): self.reset() self.prep_run(cmd) sys.settrace(self.trace_dispatch) - if type(cmd) != types.CodeType: + if not isinstance(cmd, types.CodeType): cmd = cmd + "\n" try: try: diff --git a/Pythonwin/pywin/dialogs/login.py b/Pythonwin/pywin/dialogs/login.py index 2a3295693e..7ab3fd4e54 100644 --- a/Pythonwin/pywin/dialogs/login.py +++ b/Pythonwin/pywin/dialogs/login.py @@ -141,7 +141,7 @@ def GetPassword(title="Password", password=""): if len(sys.argv) > 2: def_userid = sys.argv[2] userid, password = GetLogin(title, def_user) - if userid == password == None: + if userid == password is None: print("User pressed Cancel") else: print("User ID: ", userid) diff --git a/Pythonwin/pywin/framework/app.py b/Pythonwin/pywin/framework/app.py index f994f99f91..b582423072 100644 --- a/Pythonwin/pywin/framework/app.py +++ b/Pythonwin/pywin/framework/app.py @@ -411,7 +411,7 @@ def Win32RawInput(prompt=None): if prompt is None: prompt = "" ret = dialog.GetSimpleInput(prompt) - if ret == None: + if ret is None: raise KeyboardInterrupt("operation cancelled") return ret diff --git a/Pythonwin/pywin/framework/mdi_pychecker.py b/Pythonwin/pywin/framework/mdi_pychecker.py index c89f33b9b9..6ae57606a2 100644 --- a/Pythonwin/pywin/framework/mdi_pychecker.py +++ b/Pythonwin/pywin/framework/mdi_pychecker.py @@ -137,11 +137,11 @@ def __delslice__(self, lo, hi): del self.dirs[lo:hi] def __add__(self, other): - if type(other) == type(self) or type(other) == type([]): + if isinstance(other, (dirpath, list)): return self.dirs + other.dirs def __radd__(self, other): - if type(other) == type(self) or type(other) == type([]): + if isinstance(other, (dirpath, list)): return other.dirs + self.dirs @@ -319,7 +319,7 @@ def idleHandler(self, handler, count): import time time.sleep(0.001) - if self.result != None: + if self.result is not None: win32ui.GetApp().DeleteIdleHandler(self.idleHandler) return 0 return 1 # more @@ -389,7 +389,7 @@ def _inactive_idleHandler(self, handler, count): lines = open(f, "r").readlines() for i in range(len(lines)): line = lines[i] - if self.pat.search(line) != None: + if self.pat.search(line) is not None: self.GetFirstView().Append(f + "(" + repr(i + 1) + ") " + line) else: self.fndx = -1 diff --git a/Pythonwin/pywin/framework/sgrepmdi.py b/Pythonwin/pywin/framework/sgrepmdi.py index b7d938bbb3..d1007a197b 100644 --- a/Pythonwin/pywin/framework/sgrepmdi.py +++ b/Pythonwin/pywin/framework/sgrepmdi.py @@ -120,11 +120,11 @@ def __delslice__(self, lo, hi): del self.dirs[lo:hi] def __add__(self, other): - if type(other) == type(self) or type(other) == type([]): + if isinstance(other, (dirpath, list)): return self.dirs + other.dirs def __radd__(self, other): - if type(other) == type(self) or type(other) == type([]): + if isinstance(other, (dirpath, list)): return other.dirs + self.dirs @@ -302,7 +302,7 @@ def SearchFile(self, handler, count): lines = open(f, "r").readlines() for i in range(len(lines)): line = lines[i] - if self.pat.search(line) != None: + if self.pat.search(line) is not None: self.GetFirstView().Append(f + "(" + repr(i + 1) + ") " + line) else: self.fndx = -1 diff --git a/Pythonwin/pywin/framework/winout.py b/Pythonwin/pywin/framework/winout.py index e78e959a9a..a55a13e374 100644 --- a/Pythonwin/pywin/framework/winout.py +++ b/Pythonwin/pywin/framework/winout.py @@ -129,7 +129,7 @@ def OnRClick(self, params): paramsList = self.GetRightMenuItems() menu = win32ui.CreatePopupMenu() for appendParams in paramsList: - if type(appendParams) != type(()): + if not isinstance(appendParams, tuple): appendParams = (appendParams,) menu.AppendMenu(*appendParams) menu.TrackPopupMenu(params[5]) # track at mouse position. @@ -377,7 +377,7 @@ def __init__( self.title = title self.bCreating = 0 self.interruptCount = 0 - if type(defSize) == type(""): # is a string - maintain size pos from ini file. + if isinstance(defSize, str): # maintain size pos from ini file. self.iniSizeSection = defSize self.defSize = app.LoadWindowSize(defSize) self.loadedSize = self.defSize diff --git a/Pythonwin/pywin/mfc/dialog.py b/Pythonwin/pywin/mfc/dialog.py index 25fe13635b..6e528d9b6a 100644 --- a/Pythonwin/pywin/mfc/dialog.py +++ b/Pythonwin/pywin/mfc/dialog.py @@ -13,9 +13,9 @@ def dllFromDll(dllid): "given a 'dll' (maybe a dll, filename, etc), return a DLL object" - if dllid == None: + if dllid is None: return None - elif type("") == type(dllid): + elif isinstance(dllid, str): return win32ui.LoadLibrary(dllid) else: try: @@ -33,7 +33,7 @@ def __init__(self, id, dllid=None): dllid may be None, a dll object, or a string with a dll name""" # must take a reference to the DLL until InitDialog. self.dll = dllFromDll(dllid) - if type(id) == type([]): # a template + if isinstance(id, list): # a template dlg = win32ui.CreateDialogIndirect(id) else: dlg = win32ui.CreateDialog(id, self.dll) @@ -114,7 +114,7 @@ def __init__( dllid=None, ): self.dll = dllFromDll(dllid) - if type(dlgID) == type([]): # a template + if isinstance(dlgID, list): # a template raise TypeError("dlgID parameter must be an integer resource ID") dlg = win32ui.CreatePrintDialog(dlgID, printSetupOnly, flags, parent, self.dll) window.Wnd.__init__(self, dlg) @@ -193,7 +193,7 @@ def __init__(self, id, dllid=None, caption=0): self.dll = dllFromDll(dllid) if self.dll: oldRes = win32ui.SetResource(self.dll) - if type(id) == type([]): + if isinstance(id, list): dlg = win32ui.CreatePropertyPageIndirect(id) else: dlg = win32ui.CreatePropertyPage(id, caption) @@ -243,7 +243,7 @@ def AddPage(self, pages): def DoAddSinglePage(self, page): "Page may be page, or int ID. Assumes DLL setup" - if type(page) == type(0): + if isinstance(page, int): self.sheet.AddPage(win32ui.CreatePropertyPage(page)) else: self.sheet.AddPage(page) diff --git a/Pythonwin/pywin/scintilla/config.py b/Pythonwin/pywin/scintilla/config.py index 9a1b210e9c..6f169eed37 100644 --- a/Pythonwin/pywin/scintilla/config.py +++ b/Pythonwin/pywin/scintilla/config.py @@ -199,7 +199,7 @@ def configure(self, editor, subsections=None): if ns: num = 0 for name, func in list(ns.items()): - if type(func) == types.FunctionType and name[:1] != "_": + if isinstance(func, types.FunctionType) and name[:1] != "_": bindings.bind(name, func) num = num + 1 trace("Configuration Extension code loaded", num, "events") diff --git a/Pythonwin/pywin/scintilla/control.py b/Pythonwin/pywin/scintilla/control.py index e58ea3fa6a..9923489b8a 100644 --- a/Pythonwin/pywin/scintilla/control.py +++ b/Pythonwin/pywin/scintilla/control.py @@ -261,7 +261,7 @@ def SCICancel(self): # AutoComplete def SCIAutoCShow(self, text): - if type(text) in [type([]), type(())]: + if isinstance(text, (list, tuple)): text = " ".join(text) buff = (text + "\0").encode(default_scintilla_encoding) return self.SendScintilla(scintillacon.SCI_AUTOCSHOW, 0, buff) @@ -423,7 +423,7 @@ def GetSelText(self): return txtBuf.tobytes()[:-1].decode(default_scintilla_encoding) def SetSel(self, start=0, end=None): - if type(start) == type(()): + if isinstance(start, tuple): assert ( end is None ), "If you pass a point in the first param, the second must be None" diff --git a/Pythonwin/pywin/scintilla/formatter.py b/Pythonwin/pywin/scintilla/formatter.py index 56100ccfcf..3687d64e00 100644 --- a/Pythonwin/pywin/scintilla/formatter.py +++ b/Pythonwin/pywin/scintilla/formatter.py @@ -36,7 +36,7 @@ def __init__(self, name, format, background=CLR_INVALID): # Default background for each style is only used when there are no # saved settings (generally on first startup) self.background = self.default_background = background - if type(format) == type(""): + if isinstance(format, str): self.aliased = format self.format = None else: diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index a60b732472..341532f575 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -25,11 +25,11 @@ # helper to get the text of an arbitary item def GetItemText(item): - if type(item) == type(()) or type(item) == type([]): + if isinstance(item, (tuple, list)): use = item[0] else: use = item - if type(use) == type(""): + if isinstance(use, str): return use else: return repr(item) @@ -185,8 +185,8 @@ def AddItem(self, parentHandle, item, hInsertAfter=commctrl.TVI_LAST): bitmapSel = self.GetSelectedBitmapColumn(item) if bitmapSel is None: bitmapSel = bitmapCol - ## if type(text) is str: - ## text = text.encode("mbcs") + ## if isinstance(text, str): + ## text = text.encode("mbcs") hitem = self.listControl.InsertItem( parentHandle, hInsertAfter, diff --git a/adodbapi/adodbapi.py b/adodbapi/adodbapi.py index 8f7c045ea7..36a2c88961 100644 --- a/adodbapi/adodbapi.py +++ b/adodbapi/adodbapi.py @@ -1208,7 +1208,7 @@ def setoutputsize(self, size, column=None): def _last_query(self): # let the programmer see what query we actually used try: - if self.parameters == None: + if self.parameters is None: ret = self.commandText else: ret = "%s,parameters=%s" % (self.commandText, repr(self.parameters)) diff --git a/adodbapi/apibase.py b/adodbapi/apibase.py index 50770c96ee..d16265917f 100644 --- a/adodbapi/apibase.py +++ b/adodbapi/apibase.py @@ -171,6 +171,7 @@ def __init__(self): # the details will be filled in by instances self._ordinal_1899_12_31 = datetime.date(1899, 12, 31).toordinal() - 1 # Use cls.types to compare if an input parameter is a datetime self.types = { + # Dynamically get the types as the methods may be overriden type(self.Date(2000, 1, 1)), type(self.Time(12, 1, 1)), type(self.Timestamp(2000, 1, 1, 12, 1, 1)), @@ -444,9 +445,8 @@ def pyTypeToADOType(d): except KeyError: # The type was not defined in the pre-computed Type table from . import dateconverter - if ( - tp in dateconverter.types - ): # maybe it is one of our supported Date/Time types + # maybe it is one of our supported Date/Time types + if tp in dateconverter.types: return adc.adDate # otherwise, attempt to discern the type by probing the data object itself -- to handle duck typing if isinstance(d, StringTypes): diff --git a/adodbapi/remote/server.py b/adodbapi/remote/server.py index 3cce1d8ab4..bfba3a7473 100644 --- a/adodbapi/remote/server.py +++ b/adodbapi/remote/server.py @@ -118,7 +118,7 @@ def unfixpickle(x): # for 'named' paramstyle user will pass a mapping newargs = {} for arg, val in list(x.items()): - if isinstance(arg, type(array.array("B"))): + if isinstance(arg, array.array): newargs[arg] = Binary(val) else: newargs[arg] = val @@ -126,7 +126,7 @@ def unfixpickle(x): # if not a mapping, then a sequence newargs = [] for arg in x: - if isinstance(arg, type(array.array("B"))): + if isinstance(arg, array.array): newargs.append(Binary(arg)) else: newargs.append(arg) diff --git a/adodbapi/test/adodbapitest.py b/adodbapi/test/adodbapitest.py index 4b7b352a14..d7a4f2c9bc 100644 --- a/adodbapi/test/adodbapitest.py +++ b/adodbapi/test/adodbapitest.py @@ -1025,7 +1025,7 @@ def testRollBack(self): self.conn.rollback() crsr.execute(selectSql) assert ( - crsr.fetchone() == None + crsr.fetchone() is None ), "cursor.fetchone should return None if a query retrieves no rows" crsr.execute("SELECT fldData from xx_%s" % config.tmp) rs = crsr.fetchall() @@ -1082,7 +1082,7 @@ def testAutoRollback(self): row = crsr.fetchone() except api.DatabaseError: row = None # if the entire table disappeared the rollback was perfect and the test passed - assert row == None, ( + assert row is None, ( "cursor.fetchone should return None if a query retrieves no rows. Got %s" % repr(row) ) @@ -1257,7 +1257,7 @@ def testMultipleSetReturn(self): assert crsr.nextset() == True, "third set should be present" rowdesc = crsr.fetchall() self.assertEqual(rowdesc[0][0], 8) - assert crsr.nextset() == None, "No more return sets, should return None" + assert crsr.nextset() is None, "No more return sets, should return None" self.helpRollbackTblTemp() @@ -1348,7 +1348,7 @@ def getAnotherConnection(self, addkeys=None): def testOkConnect(self): c = self.db(*config.connStrAccess[0], **config.connStrAccess[1]) - assert c != None + assert c is not None c.close() @@ -1384,7 +1384,7 @@ def getAnotherConnection(self, addkeys=None): def testOkConnect(self): c = self.db(*config.connStrMySql[0], **config.connStrMySql[1]) - assert c != None + assert c is not None # def testStoredProcedure(self): # crsr=self.conn.cursor() @@ -1450,7 +1450,7 @@ def getAnotherConnection(self, addkeys=None): def testOkConnect(self): c = self.db(*config.connStrPostgres[0], **config.connStrPostgres[1]) - assert c != None + assert c is not None # def testStoredProcedure(self): # crsr=self.conn.cursor() diff --git a/adodbapi/test/test_adodbapi_dbapi20.py b/adodbapi/test/test_adodbapi_dbapi20.py index 31bbae4827..6115138336 100644 --- a/adodbapi/test/test_adodbapi_dbapi20.py +++ b/adodbapi/test/test_adodbapi_dbapi20.py @@ -184,7 +184,7 @@ def test_nextset(self): names = cur.fetchall() assert len(names) == len(self.samples) s = cur.nextset() - assert s == None, "No more return sets, should return None" + assert s is None, "No more return sets, should return None" finally: try: self.help_nextset_tearDown(cur) diff --git a/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index 91b4b303b5..2a6b7d1c9a 100644 --- a/com/win32com/client/__init__.py +++ b/com/win32com/client/__init__.py @@ -605,7 +605,7 @@ def _get_good_object_(self, obj, obUserName=None, resultCLSID=None): # XXX - These should be consolidated with dynamic.py versions. def _get_good_single_object_(obj, obUserName=None, resultCLSID=None): - if _PyIDispatchType == type(obj): + if isinstance(obj, _PyIDispatchType): return Dispatch(obj, obUserName, resultCLSID) return obj diff --git a/com/win32com/client/build.py b/com/win32com/client/build.py index ce4e2e4aeb..dc43aae0a9 100644 --- a/com/win32com/client/build.py +++ b/com/win32com/client/build.py @@ -89,7 +89,7 @@ def __init__( resultDoc=None, hidden=0, ): - if type(desc_or_id) == type(0): + if isinstance(desc_or_id, int): self.dispid = desc_or_id self.desc = None else: @@ -546,7 +546,7 @@ def __init__(self, attr, doc): def _ResolveType(typerepr, itypeinfo): # Resolve VT_USERDEFINED (often aliases or typed IDispatches) - if type(typerepr) == tuple: + if isinstance(typerepr, tuple): indir_vt, subrepr = typerepr if indir_vt == pythoncom.VT_PTR: # If it is a VT_PTR to a VT_USERDEFINED that is an IDispatch/IUnknown, @@ -556,7 +556,9 @@ def _ResolveType(typerepr, itypeinfo): # eg, (VT_PTR, (VT_USERDEFINED, somehandle)) needs to become VT_DISPATCH # only when "somehandle" is an object. # but (VT_PTR, (VT_USERDEFINED, otherhandle)) doesnt get the indirection dropped. - was_user = type(subrepr) == tuple and subrepr[0] == pythoncom.VT_USERDEFINED + was_user = ( + isinstance(subrepr, tuple) and subrepr[0] == pythoncom.VT_USERDEFINED + ) subrepr, sub_clsid, sub_doc = _ResolveType(subrepr, itypeinfo) if was_user and subrepr in [ pythoncom.VT_DISPATCH, @@ -701,7 +703,7 @@ def MakeDefaultArgRepr(defArgVal): # VARIANT <-> SYSTEMTIME conversions always lose any sub-second # resolution, so just use a 'timetuple' here. return repr(tuple(val.utctimetuple())) - if type(val) is TimeType: + if isinstance(val, TimeType): # must be the 'old' pywintypes time object... year = val.year month = val.month diff --git a/com/win32com/client/combrowse.py b/com/win32com/client/combrowse.py index 10eeaedfdb..be2e7805e0 100644 --- a/com/win32com/client/combrowse.py +++ b/com/win32com/client/combrowse.py @@ -59,7 +59,7 @@ def CalculateIsExpandable(self): class HLICLSID(HLICOM): def __init__(self, myobject, name=None): - if type(myobject) == type(""): + if isinstance(myobject, str): myobject = pythoncom.MakeIID(myobject) if name is None: try: @@ -457,7 +457,7 @@ def MakeReturnTypeName(self, typ): return typname def MakeReturnType(self, returnTypeDesc): - if type(returnTypeDesc) == type(()): + if isinstance(returnTypeDesc, tuple): first = returnTypeDesc[0] result = self.MakeReturnType(first) if first != pythoncom.VT_USERDEFINED: diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index 3eba075fa3..8cda87debd 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -161,9 +161,8 @@ def __init__(self, typeinfo, attr, doc=None, bForUser=1): ai = attr[14] self.attr = attr - if type(ai) == type(()) and type(ai[1]) == type( - 0 - ): # XXX - This is a hack - why tuples? Need to resolve? + # XXX - This is a hack - why tuples? Need to resolve? + if isinstance(ai, tuple) and isinstance(ai[1], int): href = ai[1] alinfo = typeinfo.GetRefTypeInfo(href) self.aliasDoc = alinfo.GetDocumentation(-1) @@ -184,7 +183,7 @@ def WriteAliasItem(self, aliasDict, stream): print(self.doc[0] + " = " + depName, file=stream) else: ai = self.attr[14] - if type(ai) == type(0): + if isinstance(ai, int): try: typeStr = mapVTToTypeString[ai] print("# %s=%s" % (self.doc[0], typeStr), file=stream) diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index 041f18a457..e06e61eb8d 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -348,7 +348,7 @@ def GenerateChildFromTypeLibSpec( verboseLevel = ( 0 # By default, we use no gui, and no verbose level for the children. ) - if type(typelibInfo) == type(()): + if isinstance(typelibInfo, tuple): typelibCLSID, lcid, major, minor = typelibInfo tlb = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid) else: diff --git a/com/win32com/client/util.py b/com/win32com/client/util.py index c5762951de..1925843ab3 100644 --- a/com/win32com/client/util.py +++ b/com/win32com/client/util.py @@ -16,7 +16,7 @@ def WrapEnum(ob, resultCLSID=None): (which may be either a class instance, or a dynamic.Dispatch type object). """ - if type(ob) != pythoncom.TypeIIDs[pythoncom.IID_IEnumVARIANT]: + if not isinstance(ob, pythoncom.TypeIIDs[pythoncom.IID_IEnumVARIANT]): ob = ob.QueryInterface(pythoncom.IID_IEnumVARIANT) return EnumVARIANT(ob, resultCLSID) @@ -44,7 +44,7 @@ def __call__(self, index): return self.__GetIndex(index) def __GetIndex(self, index): - if type(index) != type(0): + if not isinstance(index, int): raise TypeError("Only integer indexes are supported for enumerators") # NOTE # In this context, self.index is users purely as a flag to say diff --git a/com/win32com/server/policy.py b/com/win32com/server/policy.py index 8105e180a2..4184b0f8c8 100644 --- a/com/win32com/server/policy.py +++ b/com/win32com/server/policy.py @@ -259,7 +259,7 @@ def _wrap_(self, object): self._com_interfaces_ = [] # Allow interfaces to be specified by name. for i in ob._com_interfaces_: - if type(i) != pywintypes.IIDType: + if not isinstance(i, pywintypes.IIDType): # Prolly a string! if i[0] != "{": i = pythoncom.InterfaceNames[i] @@ -295,7 +295,7 @@ def _Invoke_(self, dispid, lcid, wFlags, args): This calls the _invoke_ helper. """ # Translate a possible string dispid to real dispid. - if type(dispid) == type(""): + if isinstance(dispid, str): try: dispid = self._name_to_dispid_[dispid.lower()] except KeyError: @@ -347,7 +347,7 @@ def _InvokeEx_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider): This calls the _invokeex_ helper. """ # Translate a possible string dispid to real dispid. - if type(dispid) == type(""): + if isinstance(dispid, str): try: dispid = self._name_to_dispid_[dispid.lower()] except KeyError: @@ -507,7 +507,7 @@ def _wrap_(self, ob): interfaces = [ i for i in getattr(ob, "_com_interfaces_", []) - if type(i) != pywintypes.IIDType and not i.startswith("{") + if not isinstance(i, pywintypes.IIDType) and not i.startswith("{") ] universal_data = universal.RegisterInterfaces( tlb_guid, tlb_lcid, tlb_major, tlb_minor, interfaces @@ -652,7 +652,7 @@ def _invokeex_(self, dispid, lcid, wFlags, args, kwArgs, serviceProvider): except KeyError: raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) # not found retob = getattr(self._obj_, name) - if type(retob) == types.MethodType: # a method as a property - call it. + if isinstance(retob, types.MethodType): # a method as a property - call it. retob = retob(*args) return retob @@ -663,11 +663,10 @@ def _invokeex_(self, dispid, lcid, wFlags, args, kwArgs, serviceProvider): raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) # read-only # If we have a method of that name (ie, a property get function), and # we have an equiv. property set function, use that instead. - if ( - type(getattr(self._obj_, name, None)) == types.MethodType - and type(getattr(self._obj_, "Set" + name, None)) == types.MethodType + fn = getattr(self._obj_, "Set" + name, None) + if isinstance(fn, types.MethodType) and isinstance( + getattr(self._obj_, name, None), types.MethodType ): - fn = getattr(self._obj_, "Set" + name) fn(*args) else: # just set the attribute @@ -691,12 +690,11 @@ class EventHandlerPolicy(DesignatedWrapPolicy): def _transform_args_(self, args, kwArgs, dispid, lcid, wFlags, serviceProvider): ret = [] for arg in args: - arg_type = type(arg) - if arg_type == IDispatchType: + if isinstance(arg, IDispatchType): import win32com.client arg = win32com.client.Dispatch(arg) - elif arg_type == IUnknownType: + elif isinstance(arg, IUnknownType): try: import win32com.client diff --git a/com/win32com/servers/PythonTools.py b/com/win32com/servers/PythonTools.py index 7f8f4d7609..1a84a7ccdf 100644 --- a/com/win32com/servers/PythonTools.py +++ b/com/win32com/servers/PythonTools.py @@ -14,7 +14,7 @@ def reload(self, module): return "no reload performed." def adddir(self, dir): - if type(dir) == type(""): + if isinstance(dir, str): sys.path.append(dir) return str(sys.path) diff --git a/com/win32com/servers/dictionary.py b/com/win32com/servers/dictionary.py index 28596b81a1..c8ec986377 100644 --- a/com/win32com/servers/dictionary.py +++ b/com/win32com/servers/dictionary.py @@ -75,7 +75,7 @@ def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider): ) key = args[0] - if type(key) not in [str, str]: + if not isinstance(key, str): ### the nArgErr thing should be 0-based, not reversed... sigh raise COMException( desc="Key must be a string", scode=winerror.DISP_E_TYPEMISMATCH diff --git a/com/win32com/servers/interp.py b/com/win32com/servers/interp.py index b15cede763..9636837b85 100644 --- a/com/win32com/servers/interp.py +++ b/com/win32com/servers/interp.py @@ -32,14 +32,14 @@ def __init__(self): def Eval(self, exp): """Evaluate an expression.""" - if type(exp) != str: + if not isinstance(exp, str): raise Exception(desc="Must be a string", scode=winerror.DISP_E_TYPEMISMATCH) return eval(str(exp), self.dict) def Exec(self, exp): """Execute a statement.""" - if type(exp) != str: + if not isinstance(exp, str): raise Exception(desc="Must be a string", scode=winerror.DISP_E_TYPEMISMATCH) exec(str(exp), self.dict) diff --git a/com/win32com/test/GenTestScripts.py b/com/win32com/test/GenTestScripts.py index 73bb26411c..4e5cf4a492 100644 --- a/com/win32com/test/GenTestScripts.py +++ b/com/win32com/test/GenTestScripts.py @@ -68,13 +68,13 @@ def CleanAll(): name = args[0] + ".py" os.unlink(os.path.join(genPath, name)) except os.error as details: - if type(details) == type(()) and details[0] != 2: + if isinstance(details, tuple) and details[0] != 2: print("Could not deleted generated", name, details) try: name = args[0] + ".pyc" os.unlink(os.path.join(genPath, name)) except os.error as details: - if type(details) == type(()) and details[0] != 2: + if isinstance(details, tuple) and details[0] != 2: print("Could not deleted generated", name, details) try: os.unlink(os.path.join(genPath, "__init__.py")) diff --git a/com/win32com/test/testArrays.py b/com/win32com/test/testArrays.py index f395a4131a..aa4ad16af4 100644 --- a/com/win32com/test/testArrays.py +++ b/com/win32com/test/testArrays.py @@ -41,7 +41,7 @@ def _normalize_array(a): - if type(a) != type(()): + if not isinstance(a, tuple): return a ret = [] for i in a: diff --git a/com/win32com/test/testDynamic.py b/com/win32com/test/testDynamic.py index 2fd9197249..8dd1d82a67 100644 --- a/com/win32com/test/testDynamic.py +++ b/com/win32com/test/testDynamic.py @@ -18,7 +18,7 @@ def _dynamic_(self, name, lcid, wFlags, args): try: # to avoid problems with byref param handling, tuple results are converted to lists. ret = self.__dict__[name] - if type(ret) == type(()): + if isinstance(ret, tuple): ret = list(ret) return ret except KeyError: # Probably a method request. diff --git a/com/win32com/test/testIterators.py b/com/win32com/test/testIterators.py index b75a78dfcd..8eba364a70 100644 --- a/com/win32com/test/testIterators.py +++ b/com/win32com/test/testIterators.py @@ -128,7 +128,7 @@ def suite(): suite = unittest.TestSuite() for item in list(globals().values()): if ( - type(item) == type(unittest.TestCase) + isinstance(item, type) and issubclass(item, unittest.TestCase) and item != _BaseTestCase ): diff --git a/com/win32com/test/testMSOfficeEvents.py b/com/win32com/test/testMSOfficeEvents.py index c173c3ef1d..e677afc67f 100644 --- a/com/win32com/test/testMSOfficeEvents.py +++ b/com/win32com/test/testMSOfficeEvents.py @@ -14,14 +14,16 @@ def TestExcel(): class ExcelEvents: def OnNewWorkbook(self, wb): - if type(wb) != types.InstanceType: + if not isinstance(wb, types.InstanceType): raise RuntimeError( "The transformer doesnt appear to have translated this for us!" ) self.seen_events["OnNewWorkbook"] = None def OnWindowActivate(self, wb, wn): - if type(wb) != types.InstanceType or type(wn) != types.InstanceType: + if not isinstance(wb, types.InstanceType) or not isinstance( + wn, types.InstanceType + ): raise RuntimeError( "The transformer doesnt appear to have translated this for us!" ) diff --git a/com/win32com/test/testPersist.py b/com/win32com/test/testPersist.py index 1371498cc8..6dde9c168d 100644 --- a/com/win32com/test/testPersist.py +++ b/com/win32com/test/testPersist.py @@ -118,7 +118,7 @@ def SetIStorage(self, IStorage): def SaveObject(self): print("SaveObject") - if self.IPersistStorage != None and self.IStorage != None: + if self.IPersistStorage is not None and self.IStorage is not None: self.IPersistStorage.Save(self.IStorage, 1) self.IStorage.Commit(0) return S_OK diff --git a/com/win32com/test/testPyComTest.py b/com/win32com/test/testPyComTest.py index aec0a6f584..e7b065b239 100644 --- a/com/win32com/test/testPyComTest.py +++ b/com/win32com/test/testPyComTest.py @@ -117,7 +117,7 @@ def OnFireWithNamedParams(self, no, a_bool, out1, out2): 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 type(a_bool) == bool, "middle param not a bool" + assert a_bool is Missing or isinstance(a_bool, bool), "middle param not a bool" return out1 + 2, out2 + 2 def _DumpFireds(self): @@ -149,7 +149,7 @@ def OnFireWithNamedParams(self, no, a_bool, out1, out2): 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 type(a_bool) == bool, "middle param not a bool" + assert a_bool is Missing or isinstance(a_bool, bool), "middle param not a bool" return out1 + 2, out2 + 2 def _DumpFireds(self): @@ -577,7 +577,7 @@ def _TestPyVariant(o, is_generated, val, checker=None): assert vt == val.varianttype, (vt, val.varianttype) # Handle our safe-array test - if the passed value is a list of variants, # compare against the actual values. - if type(val.value) in (tuple, list): + if isinstance(val.value, (tuple, list)): check = [v.value if isinstance(v, VARIANT) else v for v in val.value] # pythoncom always returns arrays as tuples. got = list(got) diff --git a/com/win32com/test/testvb.py b/com/win32com/test/testvb.py index 5a3d2f73d4..369bdca859 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -178,7 +178,7 @@ def _DoTestCollection(vbtest, col_name, expected): # It sucks that some objects allow "Count()", but others "Count" def _getcount(ob): r = getattr(ob, "Count") - if type(r) != type(0): + if isinstance(r, Callable): return r() return r @@ -424,7 +424,7 @@ def TestStructs(vbtest): # Now do some object equality tests. assert s == s - assert s != None + assert s is not None if sys.version_info > (3, 0): try: s < None @@ -525,9 +525,9 @@ def TestObjectSemantics(ob): assert ob._oleobj_ == ob._oleobj_.QueryInterface(pythoncom.IID_IUnknown) assert not ob._oleobj_ != ob._oleobj_.QueryInterface(pythoncom.IID_IUnknown) - assert ob._oleobj_ != None + assert ob._oleobj_ is not None assert None != ob._oleobj_ - assert ob != None + assert ob is not None assert None != ob if sys.version_info > (3, 0): try: diff --git a/com/win32com/universal.py b/com/win32com/universal.py index 7c2944ed10..f7d86e4dde 100644 --- a/com/win32com/universal.py +++ b/com/win32com/universal.py @@ -206,7 +206,7 @@ def dispatch( retVal = ob._InvokeEx_(meth.dispid, 0, meth.invkind, args, None, None) # None is an allowed return value stating that # the code doesn't want to touch any output arguments. - if type(retVal) == tuple: # Like pythoncom, we special case a tuple. + if isinstance(retVal, tuple): # Like pythoncom, we special case a tuple. # However, if they want to return a specific HRESULT, # then they have to return all of the out arguments # AND the HRESULT. diff --git a/com/win32comext/adsi/__init__.py b/com/win32comext/adsi/__init__.py index ab95196f68..69b4c53c33 100644 --- a/com/win32comext/adsi/__init__.py +++ b/com/win32comext/adsi/__init__.py @@ -1,7 +1,7 @@ import win32com import win32com.client -if type(__path__) == type(""): +if isinstance(__path__, str): # For freeze to work! import sys @@ -62,7 +62,7 @@ def __call__(self, index): return self.__GetIndex(index) def __GetIndex(self, index): - if type(index) != type(0): + if not isinstance(index, int): raise TypeError("Only integer indexes are supported for enumerators") if index != self.index + 1: # Index requested out of sequence. diff --git a/com/win32comext/adsi/demos/scp.py b/com/win32comext/adsi/demos/scp.py index d1a4ca05ec..cc96e5a878 100644 --- a/com/win32comext/adsi/demos/scp.py +++ b/com/win32comext/adsi/demos/scp.py @@ -219,7 +219,7 @@ def SpnRegister( spns, # List of SPNs to register operation, # Add, replace, or delete SPNs ): - assert type(spns) not in [str, str] and hasattr(spns, "__iter__"), ( + assert not isinstance(spns, str) and hasattr(spns, "__iter__"), ( "spns must be a sequence of strings (got %r)" % spns ) # Bind to a domain controller. diff --git a/com/win32comext/adsi/demos/test.py b/com/win32comext/adsi/demos/test.py index a1dba34dc5..d5b8fde98e 100644 --- a/com/win32comext/adsi/demos/test.py +++ b/com/win32comext/adsi/demos/test.py @@ -231,7 +231,7 @@ def main(): tests = [] for ob in globals().values(): - if type(ob) == type(main) and ob.__doc__: + if isinstance(ob, Callable) and ob.__doc__: tests.append(ob) opts, args = getopt.getopt(sys.argv[1:], "s:hv") for opt, val in opts: diff --git a/com/win32comext/axdebug/codecontainer.py b/com/win32comext/axdebug/codecontainer.py index c390955681..44c5f0e797 100644 --- a/com/win32comext/axdebug/codecontainer.py +++ b/com/win32comext/axdebug/codecontainer.py @@ -261,7 +261,7 @@ def GetName(self, dnt): attrs = sc.GetSyntaxColorAttributes() attrlen = 0 for attr in attrs: - if type(attr) == type(()): + if isinstance(attr, tuple): attrlen = attrlen + attr[1] else: attrlen = attrlen + 1 diff --git a/com/win32comext/axscript/client/error.py b/com/win32comext/axscript/client/error.py index 1dfa54fa2f..8ab7ec787a 100644 --- a/com/win32comext/axscript/client/error.py +++ b/com/win32comext/axscript/client/error.py @@ -202,8 +202,8 @@ def _BuildFromOther(self, site, exc_type, value, tb): # don't have a decode method... if sys.version_info < (3,): for i in range(len(bits)): - if type(bits[i]) is str: - # assert type(bits[i]) is str, type(bits[i]) + if isinstance(bits[i], str): + # assert isinstance(bits[i], str), type(bits[i]) bits[i] = bits[i].decode("utf8") self.description = ExpandTabs("".join(bits)) diff --git a/com/win32comext/axscript/client/framework.py b/com/win32comext/axscript/client/framework.py index d7b56a7cbe..2274f4e089 100644 --- a/com/win32comext/axscript/client/framework.py +++ b/com/win32comext/axscript/client/framework.py @@ -356,7 +356,7 @@ def Register(self): # id = self.parentItem.dispatch.GetIDsOfNames(self.name) # print "DispID of me is", id # result = self.parentItem.dispatch.Invoke(id, 0, pythoncom.DISPATCH_PROPERTYGET,1) - # if type(result)==pythoncom.TypeIIDs[pythoncom.IID_IDispatch]: + # if isinstance(result, pythoncom.TypeIIDs[pythoncom.IID_IDispatch]): # self.dispatch = result # else: # print "*** No dispatch" @@ -509,7 +509,9 @@ def FindBuildSubItemEvents(self): # as no event handler for "top" would work. # I think we simply need to connect to a *single* event handler. # As use in IE is deprecated, I am not solving this now. - if type(result) == pythoncom.TypeIIDs[pythoncom.IID_IDispatch]: + if isinstance( + result, pythoncom.TypeIIDs[pythoncom.IID_IDispatch] + ): name = names[0] subObj = self.GetCreateSubItem( self, name, result, axscript.SCRIPTITEM_ISVISIBLE diff --git a/com/win32comext/axscript/client/pyscript.py b/com/win32comext/axscript/client/pyscript.py index d2b21b58e1..5cbcffe3af 100644 --- a/com/win32comext/axscript/client/pyscript.py +++ b/com/win32comext/axscript/client/pyscript.py @@ -333,7 +333,7 @@ def DoProcessScriptItemEvent(self, item, event, lcid, wFlags, args): codeBlock = function = None try: function = item.scriptlets[funcName] - if type(function) == type(self): # ie, is a CodeBlock instance + if isinstance(function, PyScript): # ie, is a CodeBlock instance codeBlock = function function = None except KeyError: diff --git a/com/win32comext/axscript/client/scriptdispatch.py b/com/win32comext/axscript/client/scriptdispatch.py index 525326e7d6..c1989dc286 100644 --- a/com/win32comext/axscript/client/scriptdispatch.py +++ b/com/win32comext/axscript/client/scriptdispatch.py @@ -21,7 +21,7 @@ def _is_callable(obj): - return type(obj) in [types.FunctionType, types.MethodType] + return isinstance(obj, (types.FunctionType, types.MethodType)) # ignore hasattr(obj, "__call__") as this means all COM objects! @@ -44,7 +44,7 @@ def _dynamic_(self, name, lcid, wFlags, args): raise AttributeError(name) # Not a function. realArgs = [] for arg in args: - if type(arg) == PyIDispatchType: + if isinstance(arg, PyIDispatchType): realArgs.append(Dispatch(arg)) else: realArgs.append(arg) diff --git a/com/win32comext/axscript/server/axsite.py b/com/win32comext/axscript/server/axsite.py index d07ed120d0..8f0dd33b17 100644 --- a/com/win32comext/axscript/server/axsite.py +++ b/com/win32comext/axscript/server/axsite.py @@ -8,7 +8,7 @@ class AXEngine: def __init__(self, site, engine): self.eScript = self.eParse = self.eSafety = None - if type(engine) == type(""): + if isinstance(engine, str): engine = pythoncom.CoCreateInstance( engine, None, pythoncom.CLSCTX_SERVER, pythoncom.IID_IUnknown ) @@ -87,7 +87,7 @@ def AddEngine(self, engine): """Adds a new engine to the site. engine can be a string, or a fully wrapped engine object. """ - if type(engine) == type(""): + if isinstance(engine, str): newEngine = AXEngine(util.wrap(self), engine) else: newEngine = engine diff --git a/com/win32comext/directsound/test/ds_test.py b/com/win32comext/directsound/test/ds_test.py index 84259ee2b0..1a4d5f94e1 100644 --- a/com/win32comext/directsound/test/ds_test.py +++ b/com/win32comext/directsound/test/ds_test.py @@ -77,7 +77,7 @@ class WAVEFORMATTest(unittest.TestCase): def test_1_Type(self): "WAVEFORMATEX type" w = pywintypes.WAVEFORMATEX() - self.assertTrue(type(w) == pywintypes.WAVEFORMATEXType) + self.assertTrue(isinstance(w, pywintypes.WAVEFORMATEXType)) def test_2_Attr(self): "WAVEFORMATEX attribute access" @@ -102,7 +102,7 @@ class DSCAPSTest(unittest.TestCase): def test_1_Type(self): "DSCAPS type" c = ds.DSCAPS() - self.assertTrue(type(c) == ds.DSCAPSType) + self.assertTrue(isinstance(c, ds.DSCAPSType)) def test_2_Attr(self): "DSCAPS attribute access" @@ -156,7 +156,7 @@ class DSBCAPSTest(unittest.TestCase): def test_1_Type(self): "DSBCAPS type" c = ds.DSBCAPS() - self.assertTrue(type(c) == ds.DSBCAPSType) + self.assertTrue(isinstance(c, ds.DSBCAPSType)) def test_2_Attr(self): "DSBCAPS attribute access" @@ -176,7 +176,7 @@ class DSCCAPSTest(unittest.TestCase): def test_1_Type(self): "DSCCAPS type" c = ds.DSCCAPS() - self.assertTrue(type(c) == ds.DSCCAPSType) + self.assertTrue(isinstance(c, ds.DSCCAPSType)) def test_2_Attr(self): "DSCCAPS attribute access" @@ -194,7 +194,7 @@ class DSCBCAPSTest(unittest.TestCase): def test_1_Type(self): "DSCBCAPS type" c = ds.DSCBCAPS() - self.assertTrue(type(c) == ds.DSCBCAPSType) + self.assertTrue(isinstance(c, ds.DSCBCAPSType)) def test_2_Attr(self): "DSCBCAPS attribute access" @@ -210,7 +210,7 @@ class DSBUFFERDESCTest(unittest.TestCase): def test_1_Type(self): "DSBUFFERDESC type" c = ds.DSBUFFERDESC() - self.assertTrue(type(c) == ds.DSBUFFERDESCType) + self.assertTrue(isinstance(c, ds.DSBUFFERDESCType)) def test_2_Attr(self): "DSBUFFERDESC attribute access" @@ -247,7 +247,7 @@ class DSCBUFFERDESCTest(unittest.TestCase): def test_1_Type(self): "DSCBUFFERDESC type" c = ds.DSCBUFFERDESC() - self.assertTrue(type(c) == ds.DSCBUFFERDESCType) + self.assertTrue(isinstance(c, ds.DSCBUFFERDESCType)) def test_2_Attr(self): "DSCBUFFERDESC attribute access" diff --git a/com/win32comext/ifilter/demo/filterDemo.py b/com/win32comext/ifilter/demo/filterDemo.py index 30742d8a3b..1eb7a01c0e 100644 --- a/com/win32comext/ifilter/demo/filterDemo.py +++ b/com/win32comext/ifilter/demo/filterDemo.py @@ -291,7 +291,7 @@ def _usage(): reduce(operator.add, [len(p) for p in propValue]), ) ) - elif type(propValue) == type([]): + elif isinstance(propValue, list): print() for pv in propValue: print(pv) diff --git a/com/win32comext/mapi/__init__.py b/com/win32comext/mapi/__init__.py index 3933e21288..d15a79e1f9 100644 --- a/com/win32comext/mapi/__init__.py +++ b/com/win32comext/mapi/__init__.py @@ -1,4 +1,4 @@ -if type(__path__) == type(""): +if isinstance(__path__, str): # For freeze to work! import sys diff --git a/com/win32comext/mapi/mapiutil.py b/com/win32comext/mapi/mapiutil.py index c9519414aa..8a5ffb6323 100644 --- a/com/win32comext/mapi/mapiutil.py +++ b/com/win32comext/mapi/mapiutil.py @@ -103,13 +103,13 @@ def GetProperties(obj, propList): If the property fetch fails, the result is None. """ bRetList = 1 - if type(propList) not in [TupleType, ListType]: + if not isinstance(propList, (TupleType, ListType)): bRetList = 0 propList = (propList,) realPropList = [] rc = [] for prop in propList: - if type(prop) != IntType: # Integer + if not isinstance(prop, IntType): # Integer props = ((mapi.PS_PUBLIC_STRINGS, prop),) propIds = obj.GetIDsFromNames(props, 0) prop = mapitags.PROP_TAG( @@ -134,7 +134,7 @@ def GetAllProperties(obj, make_tag_names=True): for tag, val in data: if make_tag_names: hr, tags, array = obj.GetNamesFromIDs((tag,)) - if type(array[0][1]) == type(""): + if isinstance(array[0][1], str): name = array[0][1] else: name = GetPropTagName(tag) @@ -157,7 +157,7 @@ def GetAllProperties(obj, make_tag_names=True): def SetPropertyValue(obj, prop, val): - if type(prop) != IntType: + if not isinstance(prop, IntType): props = ((mapi.PS_PUBLIC_STRINGS, prop),) propIds = obj.GetIDsFromNames(props, mapi.MAPI_CREATE) if val == (1 == 1) or val == (1 == 0): @@ -190,7 +190,7 @@ def SetProperties(msg, propDict): newProps = [] # First pass over the properties we should get IDs for. for key, val in propDict.items(): - if type(key) == str: + if isinstance(key, str): newProps.append((mapi.PS_PUBLIC_STRINGS, key)) # Query for the new IDs if newProps: @@ -198,18 +198,17 @@ def SetProperties(msg, propDict): newIdNo = 0 newProps = [] for key, val in propDict.items(): - if type(key) == str: - type_val = type(val) - if type_val == str: + if isinstance(key, str): + if isinstance(val, str): tagType = mapitags.PT_UNICODE - elif type_val == IntType: + elif isinstance(val, int): tagType = mapitags.PT_I4 - elif type_val == TimeType: + elif isinstance(val, TimeType): tagType = mapitags.PT_SYSTIME else: raise ValueError( "The type of object %s(%s) can not be written" - % (repr(val), type_val) + % (repr(val), type(val)) ) key = mapitags.PROP_TAG(tagType, mapitags.PROP_ID(newIds[newIdNo])) newIdNo = newIdNo + 1 diff --git a/com/win32comext/shell/demos/servers/empty_volume_cache.py b/com/win32comext/shell/demos/servers/empty_volume_cache.py index a257ac1756..a10d150e9f 100644 --- a/com/win32comext/shell/demos/servers/empty_volume_cache.py +++ b/com/win32comext/shell/demos/servers/empty_volume_cache.py @@ -93,7 +93,7 @@ def _WalkCallback(self, arg, directory, files): for file in files: fqn = os.path.join(directory, file).lower() if file.endswith(".pyc") or file.endswith(".pyo"): - # See below - total_list == None means delete files, + # See below - total_list is None means delete files, # otherwise it is a list where the result is stored. Its a # list simply due to the way os.walk works - only [0] is # referenced diff --git a/com/win32comext/shell/demos/servers/shell_view.py b/com/win32comext/shell/demos/servers/shell_view.py index 7d8bc51bae..29b66ac573 100644 --- a/com/win32comext/shell/demos/servers/shell_view.py +++ b/com/win32comext/shell/demos/servers/shell_view.py @@ -853,7 +853,7 @@ def CreateViewWindow(self, prev, settings, browser, rect): self._SetupLexer() self._SendSci(scintillacon.SCI_ADDTEXT, len(file_data), file_data) - if self.lineno != None: + if self.lineno is not None: self._SendSci(scintillacon.SCI_GOTOLINE, self.lineno) print("Scintilla's hwnd is", self.hwnd) diff --git a/win32/Demos/FileSecurityTest.py b/win32/Demos/FileSecurityTest.py index 90c454833f..3b8940b644 100644 --- a/win32/Demos/FileSecurityTest.py +++ b/win32/Demos/FileSecurityTest.py @@ -45,7 +45,7 @@ # get ACEs sd = win32security.GetFileSecurity(name, win32security.DACL_SECURITY_INFORMATION) dacl = sd.GetSecurityDescriptorDacl() -if dacl == None: +if dacl is None: print("No Discretionary ACL") else: for ace_no in range(0, dacl.GetAceCount()): diff --git a/win32/Demos/rastest.py b/win32/Demos/rastest.py index 669a2a800b..e737acd9de 100644 --- a/win32/Demos/rastest.py +++ b/win32/Demos/rastest.py @@ -156,7 +156,7 @@ def main(): ShowConnections() if opt == "-c": hras, rc = Connect(val, bCallback) - if hras != None: + if hras is not None: print("hras: 0x%8lx, rc: 0x%04x" % (hras, rc)) if opt == "-d": Disconnect(val) diff --git a/win32/Demos/security/explicit_entries.py b/win32/Demos/security/explicit_entries.py index b04f45173f..be37ee047c 100644 --- a/win32/Demos/security/explicit_entries.py +++ b/win32/Demos/security/explicit_entries.py @@ -56,10 +56,10 @@ sd = win32security.GetFileSecurity(fname, all_security_info) old_sacl = sd.GetSecurityDescriptorSacl() -if old_sacl == None: +if old_sacl is None: old_sacl = win32security.ACL() old_dacl = sd.GetSecurityDescriptorDacl() -if old_dacl == None: +if old_dacl is None: old_dacl = win32security.ACL() my_sid = win32security.GetTokenInformation(th, ntsecuritycon.TokenUser)[0] diff --git a/win32/Demos/win32clipboardDemo.py b/win32/Demos/win32clipboardDemo.py index e3a3fab03a..c65f546643 100644 --- a/win32/Demos/win32clipboardDemo.py +++ b/win32/Demos/win32clipboardDemo.py @@ -44,7 +44,9 @@ def TestText(): # CF_UNICODE text always gives unicode objects back. got = GetClipboardData(win32con.CF_UNICODETEXT) assert got == text, "Didnt get the correct result back - '%r'." % (got,) - assert type(got) == str, "Didnt get the correct result back - '%r'." % (got,) + assert isinstance(got, str), "Didnt get the correct result back - '%r'." % ( + got, + ) # CF_OEMTEXT is a bytes-based format. got = GetClipboardData(win32con.CF_OEMTEXT) @@ -59,7 +61,9 @@ def TestText(): # Get it in Unicode. got = GetClipboardData(win32con.CF_UNICODETEXT) assert got == text, "Didnt get the correct result back - '%r'." % (got,) - assert type(got) == str, "Didnt get the correct result back - '%r'." % (got,) + assert isinstance(got, str), "Didnt get the correct result back - '%r'." % ( + got, + ) # Close and open the clipboard to ensure auto-conversions take place. finally: @@ -72,7 +76,9 @@ def TestText(): assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) # Make sure we get back the correct types. got = GetClipboardData(win32con.CF_UNICODETEXT) - assert type(got) == str, "Didnt get the correct result back - '%r'." % (got,) + assert isinstance(got, str), "Didnt get the correct result back - '%r'." % ( + got, + ) got = GetClipboardData(win32con.CF_OEMTEXT) assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,) print("Clipboard text tests worked correctly") diff --git a/win32/Demos/win32comport_demo.py b/win32/Demos/win32comport_demo.py index c0be23917e..9266292b25 100644 --- a/win32/Demos/win32comport_demo.py +++ b/win32/Demos/win32comport_demo.py @@ -49,7 +49,7 @@ def FindModem(): # A basic synchronous COM port file-like object class SerialTTY: def __init__(self, port): - if type(port) == type(0): + if isinstance(port, int): port = "COM%d" % (port,) self.handle = CreateFile( port, diff --git a/win32/Demos/win32netdemo.py b/win32/Demos/win32netdemo.py index 36c495424b..e9bca62106 100644 --- a/win32/Demos/win32netdemo.py +++ b/win32/Demos/win32netdemo.py @@ -1,6 +1,7 @@ import getopt import sys import traceback +from collections.abc import Callable import win32api import win32net @@ -229,7 +230,7 @@ def usage(tests): def main(): tests = [] for ob in list(globals().values()): - if type(ob) == type(main) and ob.__doc__: + if isinstance(ob, Callable) and ob.__doc__: tests.append(ob) opts, args = getopt.getopt(sys.argv[1:], "s:hvc") create_user = False diff --git a/win32/Lib/regutil.py b/win32/Lib/regutil.py index 1abdd551a9..db6d849af2 100644 --- a/win32/Lib/regutil.py +++ b/win32/Lib/regutil.py @@ -46,9 +46,9 @@ def SetRegistryDefaultValue(subKey, value, rootkey=None): """A helper to set the default value for a key in the registry""" if rootkey is None: rootkey = GetRootKey() - if type(value) == str: + if isinstance(value, str): typeId = win32con.REG_SZ - elif type(value) == int: + elif isinstance(value, int): typeId = win32con.REG_DWORD else: raise TypeError("Value must be string or integer - was passed " + repr(value)) diff --git a/win32/Lib/sspi.py b/win32/Lib/sspi.py index c6f92ad381..855a4c35b8 100644 --- a/win32/Lib/sspi.py +++ b/win32/Lib/sspi.py @@ -209,9 +209,8 @@ def __init__( def authorize(self, sec_buffer_in): """Perform *one* step of the client authentication process. Pass None for the first round""" - if ( - sec_buffer_in is not None - and type(sec_buffer_in) != win32security.PySecBufferDescType + if sec_buffer_in is not None and not isinstance( + sec_buffer_in, win32security.PySecBufferDescType ): # User passed us the raw data - wrap it into a SecBufferDesc sec_buffer_new = win32security.PySecBufferDescType() @@ -287,9 +286,8 @@ def __init__( def authorize(self, sec_buffer_in): """Perform *one* step of the server authentication process.""" - if ( - sec_buffer_in is not None - and type(sec_buffer_in) != win32security.PySecBufferDescType + if sec_buffer_in is not None and not isinstance( + sec_buffer_in, win32security.PySecBufferDescType ): # User passed us the raw data - wrap it into a SecBufferDesc sec_buffer_new = win32security.PySecBufferDescType() diff --git a/win32/Lib/win32rcparser.py b/win32/Lib/win32rcparser.py index fdf7f57ccd..1d90bfd717 100644 --- a/win32/Lib/win32rcparser.py +++ b/win32/Lib/win32rcparser.py @@ -250,7 +250,7 @@ def load(self, rcstream): """ self.open(rcstream) self.getToken() - while self.token != None: + while self.token is not None: self.parse() self.getToken() @@ -412,7 +412,7 @@ def parse_dialog(self, name): self.getToken() # number dlg.h = int(self.token) self.getToken() - while not (self.token == None or self.token == "" or self.token == "END"): + while not (self.token is None or self.token == "" or self.token == "END"): if self.token == "STYLE": self.dialogStyle(dlg) elif self.token == "EXSTYLE": @@ -444,7 +444,7 @@ def styles(self, defaults, defaultStyle): Not = False while ( (i % 2 == 1 and ("|" == self.token or "NOT" == self.token)) or (i % 2 == 0) - ) and not self.token == None: + ) and not self.token is None: Not = False if "NOT" == self.token: Not = True diff --git a/win32/Lib/win32serviceutil.py b/win32/Lib/win32serviceutil.py index fb1875302c..82e0a49431 100644 --- a/win32/Lib/win32serviceutil.py +++ b/win32/Lib/win32serviceutil.py @@ -375,7 +375,7 @@ def SetServiceCustomOption(serviceName, option, value): "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName, ) try: - if type(value) == type(0): + if isinstance(value, int): win32api.RegSetValueEx(key, option, 0, win32con.REG_DWORD, value) else: win32api.RegSetValueEx(key, option, 0, win32con.REG_SZ, value) @@ -441,7 +441,7 @@ def ControlService(serviceName, code, machine=None): def __FindSvcDeps(findName): - if type(findName) is pywintypes.UnicodeType: + if isinstance(findName, pywintypes.UnicodeType): findName = str(findName) dict = {} k = win32api.RegOpenKey( diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index 569ea9b941..d0b9a08d1c 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -1014,7 +1014,7 @@ def bounds(self): ) # some special values for the RangeMap - undefined_value = type(str("RangeValueUndefined"), (object,), {})() + undefined_value = type("RangeValueUndefined", (object,), {})() class Item(int): pass diff --git a/win32/scripts/ce/pysynch.py b/win32/scripts/ce/pysynch.py index 7a44e08222..c3054f0e2e 100644 --- a/win32/scripts/ce/pysynch.py +++ b/win32/scripts/ce/pysynch.py @@ -244,7 +244,7 @@ def DumpCommands(): print("%-10s - %s" % ("Command", "Description")) print("%-10s - %s" % ("-------", "-----------")) for name, item in list(globals().items()): - if type(item) == type(DumpCommands): + if isinstance(item, Callable): doc = getattr(item, "__doc__", "") if doc: lines = string.split(doc, "\n") diff --git a/win32/scripts/rasutil.py b/win32/scripts/rasutil.py index e5a8922d72..3c13d49682 100644 --- a/win32/scripts/rasutil.py +++ b/win32/scripts/rasutil.py @@ -49,7 +49,7 @@ def Connect(rasEntryName, numRetries=5): def Disconnect(handle): - if type(handle) == type(""): # have they passed a connection name? + if isinstance(handle, str): # have they passed a connection name? for info in win32ras.EnumConnections(): if info[1].lower() == handle.lower(): handle = info[0] diff --git a/win32/scripts/regsetup.py b/win32/scripts/regsetup.py index d654b84183..f04dbda766 100644 --- a/win32/scripts/regsetup.py +++ b/win32/scripts/regsetup.py @@ -328,7 +328,7 @@ def FindRegisterApp(appName, knownFiles, searchPaths): import regutil - if type(knownFiles) == type(""): + if isinstance(knownFiles, str): knownFiles = [knownFiles] paths = [] try: diff --git a/win32/test/handles.py b/win32/test/handles.py index ad607353e8..98b73625db 100644 --- a/win32/test/handles.py +++ b/win32/test/handles.py @@ -113,8 +113,8 @@ def testHandleCompareNone(self): self.assertNotEqual(h, None) self.assertNotEqual(None, h) # ensure we use both __eq__ and __ne__ ops - self.assertFalse(h == None) - self.assertTrue(h != None) + self.assertFalse(h is None) + self.assertTrue(h is not None) def testHandleCompareInt(self): h = pywintypes.HANDLE(1) diff --git a/win32/test/test_pywintypes.py b/win32/test/test_pywintypes.py index 44b5c960cb..1f9cd9e7df 100644 --- a/win32/test/test_pywintypes.py +++ b/win32/test/test_pywintypes.py @@ -93,9 +93,9 @@ def testGUID(self): def testGUIDRichCmp(self): s = "{00020400-0000-0000-C000-000000000046}" iid = pywintypes.IID(s) - self.assertFalse(s == None) + self.assertFalse(s is None) self.assertFalse(None == s) - self.assertTrue(s != None) + self.assertTrue(s is not None) self.assertTrue(None != s) if sys.version_info > (3, 0): self.assertRaises(TypeError, operator.gt, None, s) diff --git a/win32/test/test_security.py b/win32/test/test_security.py index 42a82a134d..dc80fb4295 100644 --- a/win32/test/test_security.py +++ b/win32/test/test_security.py @@ -39,9 +39,9 @@ def testNESID(self): self.assertTrue(self.pwr_sid != self.admin_sid) def testNEOther(self): - self.assertTrue(self.pwr_sid != None) + self.assertTrue(self.pwr_sid is not None) self.assertTrue(None != self.pwr_sid) - self.assertFalse(self.pwr_sid == None) + self.assertFalse(self.pwr_sid is None) self.assertFalse(None == self.pwr_sid) self.assertNotEqual(None, self.pwr_sid) diff --git a/win32/test/test_win32api.py b/win32/test/test_win32api.py index 416f310222..81b2fe5ef9 100644 --- a/win32/test/test_win32api.py +++ b/win32/test/test_win32api.py @@ -154,7 +154,7 @@ def testShortLongPathNames(self): self.assertEqual(long_name, win32api.GetLongPathNameW(short_name).lower()) long_name = win32api.GetLongPathNameW(short_name).lower() self.assertTrue( - type(long_name) == str, + isinstance(long_name, str), "GetLongPathNameW returned type '%s'" % (type(long_name),), ) self.assertTrue( @@ -179,7 +179,7 @@ def testShortUnicodeNames(self): self.assertEqual(long_name, win32api.GetLongPathNameW(short_name).lower()) long_name = win32api.GetLongPathNameW(short_name).lower() self.assertTrue( - type(long_name) == str, + isinstance(long_name, str), "GetLongPathNameW returned type '%s'" % (type(long_name),), ) self.assertTrue( diff --git a/win32/test/test_win32wnet.py b/win32/test/test_win32wnet.py index 7a7301991c..11769fc926 100644 --- a/win32/test/test_win32wnet.py +++ b/win32/test/test_win32wnet.py @@ -59,14 +59,14 @@ def _checkItemAttributes(self, item, attrs): val = getattr(item, attr) if typ is int: self.assertTrue( - type(val) in (int,), "Attr %r has value %r" % (attr, val) + isinstance(val, int), "Attr %r has value %r" % (attr, val) ) 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. self.assertTrue( - type(val) in (str, str), "Attr %r has value %r" % (attr, val) + isinstance(val, str), "Attr %r has value %r" % (attr, val) ) new_val = val + " new value" else: