Skip to content

Commit 9238cc7

Browse files
authored
remove sys.version_info bridges (enthought#449)
1 parent ba1b18f commit 9238cc7

12 files changed

+56
-217
lines changed

comtypes/GUID.py

+7-20
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,10 @@
11
from ctypes import *
22
import sys
33

4-
if sys.version_info >= (2, 6):
54

6-
def binary(obj):
7-
return bytes(obj)
5+
def binary(obj):
6+
return bytes(obj)
87

9-
else:
10-
11-
def binary(obj):
12-
return buffer(obj)
13-
14-
15-
if sys.version_info >= (3, 0):
16-
text_type = str
17-
base_text_type = str
18-
else:
19-
text_type = unicode
20-
base_text_type = basestring
218

229
BYTE = c_byte
2310
WORD = c_ushort
@@ -41,10 +28,10 @@ class GUID(Structure):
4128

4229
def __init__(self, name=None):
4330
if name is not None:
44-
_CLSIDFromString(text_type(name), byref(self))
31+
_CLSIDFromString(str(name), byref(self))
4532

4633
def __repr__(self):
47-
return 'GUID("%s")' % text_type(self)
34+
return 'GUID("%s")' % str(self)
4835

4936
def __unicode__(self):
5037
p = c_wchar_p()
@@ -71,7 +58,7 @@ def __hash__(self):
7158
return hash(binary(self))
7259

7360
def copy(self):
74-
return GUID(text_type(self))
61+
return GUID(str(self))
7562

7663
@classmethod
7764
def from_progid(cls, progid):
@@ -80,11 +67,11 @@ def from_progid(cls, progid):
8067
progid = progid._reg_clsid_
8168
if isinstance(progid, cls):
8269
return progid
83-
elif isinstance(progid, base_text_type):
70+
elif isinstance(progid, str):
8471
if progid.startswith("{"):
8572
return cls(progid)
8673
inst = cls()
87-
_CLSIDFromProgID(text_type(progid), byref(inst))
74+
_CLSIDFromProgID(str(progid), byref(inst))
8875
return inst
8976
else:
9077
raise TypeError("Cannot construct guid from %r" % progid)

comtypes/__init__.py

+15-72
Original file line numberDiff line numberDiff line change
@@ -52,53 +52,6 @@
5252
)
5353

5454

55-
################################################################
56-
57-
# fmt: off
58-
def add_metaclass(metaclass):
59-
"""Class decorator from six.py for creating a class with a metaclass.
60-
61-
Copyright (c) 2010-2020 Benjamin Peterson
62-
63-
Permission is hereby granted, free of charge, to any person obtaining a copy of
64-
this software and associated documentation files (the "Software"), to deal in
65-
the Software without restriction, including without limitation the rights to
66-
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
67-
the Software, and to permit persons to whom the Software is furnished to do so,
68-
subject to the following conditions:
69-
70-
The above copyright notice and this permission notice shall be included in all
71-
copies or substantial portions of the Software.
72-
73-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
74-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
75-
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
76-
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
77-
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
78-
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
79-
"""
80-
def wrapper(cls):
81-
orig_vars = cls.__dict__.copy()
82-
slots = orig_vars.get('__slots__')
83-
if slots is not None:
84-
if isinstance(slots, text_type):
85-
slots = [slots]
86-
for slots_var in slots:
87-
orig_vars.pop(slots_var)
88-
orig_vars.pop('__dict__', None)
89-
orig_vars.pop('__weakref__', None)
90-
if hasattr(cls, '__qualname__'):
91-
orig_vars['__qualname__'] = cls.__qualname__
92-
return metaclass(cls.__name__, cls.__bases__, orig_vars)
93-
return wrapper
94-
# fmt: on
95-
96-
97-
################################################################
98-
if sys.version_info >= (3, 0):
99-
text_type = str
100-
else:
101-
text_type = unicode
10255
_all_slice = slice(None, None, None)
10356

10457

@@ -134,21 +87,16 @@ def _check_version(actual, tlib_cached_mtime=None):
13487
raise ImportError("Typelib different than module")
13588

13689

137-
if sys.version_info >= (3, 0):
138-
pythonapi.PyInstanceMethod_New.argtypes = [py_object]
139-
pythonapi.PyInstanceMethod_New.restype = py_object
140-
PyInstanceMethod_Type = type(pythonapi.PyInstanceMethod_New(id))
90+
pythonapi.PyInstanceMethod_New.argtypes = [py_object]
91+
pythonapi.PyInstanceMethod_New.restype = py_object
92+
PyInstanceMethod_Type = type(pythonapi.PyInstanceMethod_New(id))
14193

142-
def instancemethod(func, inst, cls):
143-
mth = PyInstanceMethod_Type(func)
144-
if inst is None:
145-
return mth
146-
return mth.__get__(inst)
14794

148-
else:
149-
150-
def instancemethod(func, inst, cls):
151-
return types.MethodType(func, inst, cls)
95+
def instancemethod(func, inst, cls):
96+
mth = PyInstanceMethod_Type(func)
97+
if inst is None:
98+
return mth
99+
return mth.__get__(inst)
152100

153101

154102
class ReturnHRESULT(Exception):
@@ -587,7 +535,7 @@ def _make_methods(self, methods):
587535
except KeyError:
588536
raise AttributeError("this class must define an _iid_")
589537
else:
590-
com_interface_registry[text_type(iid)] = self
538+
com_interface_registry[str(iid)] = self
591539
# create members
592540
vtbl_offset = self.__get_baseinterface_methodcount()
593541
member_gen = ComMemberGenerator(self.__name__, vtbl_offset, self._iid_)
@@ -627,8 +575,7 @@ class _compointer_meta(type(c_void_p), _cominterface_meta):
627575
# no functionality, but needed to avoid a metaclass conflict
628576

629577

630-
@add_metaclass(_compointer_meta)
631-
class _compointer_base(c_void_p):
578+
class _compointer_base(c_void_p, metaclass=_compointer_meta):
632579
"base class for COM interface pointer classes"
633580

634581
def __del__(self, _debug=logger.debug):
@@ -757,7 +704,7 @@ def from_param(cls, value):
757704
# IDL stuff
758705

759706

760-
class helpstring(text_type):
707+
class helpstring(str):
761708
"Specifies the helpstring for a COM method or property."
762709

763710

@@ -830,7 +777,7 @@ def COMMETHOD(idlflags, restype, methodname, *argspec):
830777

831778
if TYPE_CHECKING:
832779

833-
class _IUnknown_Base(c_void_p):
780+
class _IUnknown_Base(c_void_p, metaclass=_cominterface_meta):
834781
"""This is workaround to avoid false-positive of static type checking.
835782
836783
`IUnknown` behaves as a ctypes type, and `POINTER` can take it.
@@ -848,8 +795,7 @@ class _IUnknown_Base(c_void_p):
848795
_IUnknown_Base = object
849796

850797

851-
@add_metaclass(_cominterface_meta)
852-
class IUnknown(_IUnknown_Base):
798+
class IUnknown(_IUnknown_Base, metaclass=_cominterface_meta):
853799
"""The most basic COM interface.
854800
855801
Each subclasses of IUnknown must define these class attributes:
@@ -963,9 +909,7 @@ def CoGetObject(displayname, interface):
963909
interface = IUnknown
964910
punk = POINTER(interface)()
965911
# Do we need a way to specify the BIND_OPTS parameter?
966-
_ole32.CoGetObject(
967-
text_type(displayname), None, byref(interface._iid_), byref(punk)
968-
)
912+
_ole32.CoGetObject(str(displayname), None, byref(interface._iid_), byref(punk))
969913
return punk # type: ignore
970914

971915

@@ -1236,8 +1180,7 @@ def CoCreateInstanceEx(
12361180
from comtypes._meta import _coclass_meta
12371181

12381182

1239-
@add_metaclass(_coclass_meta)
1240-
class CoClass(COMObject):
1183+
class CoClass(COMObject, metaclass=_coclass_meta):
12411184
pass
12421185

12431186

comtypes/_comobject.py

+2-10
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from _ctypes import CopyComPointer
1414
import logging
1515
import os
16+
import queue
1617
import sys
1718

1819
from comtypes import COMError, ReturnHRESULT, instancemethod, _encode_idl
@@ -37,11 +38,6 @@
3738
_warning = logger.warning
3839
_error = logger.error
3940

40-
if sys.version_info >= (3, 0):
41-
int_types = (int,)
42-
else:
43-
int_types = (int, long)
44-
4541
################################################################
4642
# COM object implementation
4743

@@ -72,7 +68,7 @@ def winerror(exc):
7268
return exc.hresult
7369
elif isinstance(exc, WindowsError):
7470
code = exc.winerror
75-
if isinstance(code, int_types):
71+
if isinstance(code, int):
7672
return code
7773
# Sometimes, a WindowsError instance has no error code. An access
7874
# violation raised by ctypes has only text, for example. In this
@@ -381,10 +377,6 @@ def run_sta(self):
381377
messageloop.run()
382378

383379
def run_mta(self):
384-
if sys.version_info >= (3, 0):
385-
import queue
386-
else:
387-
import Queue as queue
388380
self._queue = queue.Queue()
389381
self._queue.get()
390382

comtypes/automation.py

+8-29
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,6 @@ class _safearray(object):
3434
tagSAFEARRAY = None
3535

3636

37-
if sys.version_info >= (3, 0):
38-
int_types = (int,)
39-
str_types = (str,)
40-
base_text_type = str
41-
else:
42-
int_types = (int, long)
43-
str_types = (unicode, str)
44-
base_text_type = basestring
45-
4637
LCID = DWORD
4738
DISPID = LONG
4839
SCODE = LONG
@@ -262,9 +253,7 @@ def _set_value(self, value):
262253
if value is None:
263254
self.vt = VT_NULL
264255
elif (
265-
hasattr(value, "__len__")
266-
and len(value) == 0
267-
and not isinstance(value, base_text_type)
256+
hasattr(value, "__len__") and len(value) == 0 and not isinstance(value, str)
268257
):
269258
self.vt = VT_NULL
270259
# since bool is a subclass of int, this check must come before
@@ -275,7 +264,7 @@ def _set_value(self, value):
275264
elif isinstance(value, (int, c_int)):
276265
self.vt = VT_I4
277266
self._.VT_I4 = value
278-
elif isinstance(value, int_types):
267+
elif isinstance(value, int):
279268
u = self._
280269
# try VT_I4 first.
281270
u.VT_I4 = value
@@ -310,7 +299,7 @@ def _set_value(self, value):
310299
elif isinstance(value, (float, c_double)):
311300
self.vt = VT_R8
312301
self._.VT_R8 = value
313-
elif isinstance(value, str_types):
302+
elif isinstance(value, str):
314303
self.vt = VT_BSTR
315304
# do the c_wchar_p auto unicode conversion
316305
self._.c_void_p = _SysAllocStringLen(value, len(value))
@@ -633,21 +622,11 @@ class IEnumVARIANT(IUnknown):
633622
def __iter__(self):
634623
return self
635624

636-
if sys.version_info >= (3, 0):
637-
638-
def __next__(self):
639-
item, fetched = self.Next(1)
640-
if fetched:
641-
return item
642-
raise StopIteration
643-
644-
else:
645-
646-
def next(self):
647-
item, fetched = self.Next(1)
648-
if fetched:
649-
return item
650-
raise StopIteration
625+
def __next__(self):
626+
item, fetched = self.Next(1)
627+
if fetched:
628+
return item
629+
raise StopIteration
651630

652631
def __getitem__(self, index):
653632
self.Reset()

comtypes/client/_constants.py

+1-6
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,6 @@
1010
import comtypes.automation
1111
import comtypes.typeinfo
1212

13-
if sys.version_info >= (3, 0):
14-
base_text_type = str
15-
else:
16-
base_text_type = basestring
17-
1813

1914
class _frozen_attr_dict(dict):
2015
__slots__ = ()
@@ -78,7 +73,7 @@ class Constants(object):
7873
__slots__ = ("alias", "consts", "enums", "tcomp")
7974

8075
def __init__(self, obj):
81-
if isinstance(obj, base_text_type):
76+
if isinstance(obj, str):
8277
tlib = comtypes.typeinfo.LoadTypeLibEx(obj)
8378
else:
8479
obj = obj.QueryInterface(comtypes.automation.IDispatch)

comtypes/client/_generate.py

+4-12
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,7 @@
66
import sys
77
import types
88
from typing import Any, Tuple, List, Optional, Dict, Union as _UnionT
9-
10-
if sys.version_info >= (3, 0):
11-
base_text_type = str
12-
import winreg
13-
else:
14-
base_text_type = basestring
15-
import _winreg as winreg
9+
import winreg
1610

1711
from comtypes import GUID, typeinfo
1812
import comtypes.client
@@ -46,7 +40,7 @@ def _resolve_filename(tlib_string, dirpath):
4640
(abspath, True) or (relpath, False):
4741
where relpath is an unresolved path.
4842
"""
49-
assert isinstance(tlib_string, base_text_type)
43+
assert isinstance(tlib_string, str)
5044
# pathname of type library
5145
if os.path.isabs(tlib_string):
5246
# a specific location
@@ -107,7 +101,7 @@ def GetModule(tlib):
107101
UIAutomation. The former module contains all the code, the
108102
latter is a short stub loading the former.
109103
"""
110-
if isinstance(tlib, base_text_type):
104+
if isinstance(tlib, str):
111105
tlib_string = tlib
112106
# if a relative pathname is used, we try to interpret it relative to
113107
# the directory of the calling module (if not from command line)
@@ -136,8 +130,6 @@ def GetModule(tlib):
136130
modulename = codegenerator.name_friendly_module(tlib)
137131
if modulename is None:
138132
return mod
139-
if sys.version_info < (3, 0):
140-
modulename = modulename.encode("mbcs")
141133
# create and import the friendly-named module
142134
return _create_friendly_module(tlib, modulename)
143135

@@ -146,7 +138,7 @@ def _load_tlib(obj):
146138
# type: (Any) -> typeinfo.ITypeLib
147139
"""Load a pointer of ITypeLib on demand."""
148140
# obj is a filepath or a ProgID
149-
if isinstance(obj, base_text_type):
141+
if isinstance(obj, str):
150142
# in any case, attempt to load and if tlib_string is not valid, then raise
151143
# as "OSError: [WinError -2147312566] Error loading type library/DLL"
152144
return typeinfo.LoadTypeLibEx(obj)

0 commit comments

Comments
 (0)