Skip to content

Commit 371f16b

Browse files
Remove outdated Python pre-3.9 code
These are manual fixes of src/cffi/ Co-Authored-By: mattip <matti.picus@gmail.com>
1 parent a971768 commit 371f16b

9 files changed

Lines changed: 48 additions & 89 deletions

File tree

‎src/cffi/api.py‎

Lines changed: 19 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,6 @@
33
from .error import CDefError
44
from . import model
55

6-
try:
7-
basestring
8-
except NameError:
9-
# Python 3.x
10-
basestring = str
11-
126
_unspecified = object()
137

148

@@ -36,8 +30,7 @@ def __init__(self, backend=None):
3630
select a non-default backend, mostly for tests.
3731
"""
3832
if backend is None:
39-
# You need PyPy (>= 2.0 beta), or a CPython (>= 2.6) with
40-
# _cffi_backend.so compiled.
33+
# You need PyPy or a CPython with _cffi_backend.so compiled.
4134
import _cffi_backend as backend
4235
from . import __version__
4336
if backend.__version__ != __version__:
@@ -108,7 +101,7 @@ def embedding_api(self, csource, packed=False, pack=None):
108101

109102
def _cdef(self, csource, override=False, **options):
110103
if not isinstance(csource, str): # unicode, on Python 2
111-
if not isinstance(csource, basestring):
104+
if not isinstance(csource, str):
112105
raise TypeError("cdef() argument must be a string")
113106
csource = csource.encode('ascii')
114107
with self._lock:
@@ -131,7 +124,7 @@ def dlopen(self, name, flags=0):
131124
linked to a particular library, just like C headers; in the
132125
library we only look for the actual (untyped) symbols.
133126
"""
134-
if not (isinstance(name, basestring) or
127+
if not (isinstance(name, str) or
135128
name is None or
136129
isinstance(name, self.CData)):
137130
raise TypeError("dlopen(name): name must be a file name, None, "
@@ -186,7 +179,7 @@ def typeof(self, cdecl):
186179
corresponding <ctype> object.
187180
It can also be used on 'cdata' instance to get its C type.
188181
"""
189-
if isinstance(cdecl, basestring):
182+
if isinstance(cdecl, str):
190183
return self._typeof(cdecl)
191184
if isinstance(cdecl, self.CData):
192185
return self._backend.typeof(cdecl)
@@ -204,7 +197,7 @@ def sizeof(self, cdecl):
204197
"""Return the size in bytes of the argument. It can be a
205198
string naming a C type, or a 'cdata' instance.
206199
"""
207-
if isinstance(cdecl, basestring):
200+
if isinstance(cdecl, str):
208201
BType = self._typeof(cdecl)
209202
return self._backend.sizeof(BType)
210203
else:
@@ -214,7 +207,7 @@ def alignof(self, cdecl):
214207
"""Return the natural alignment size in bytes of the C type
215208
given as a string.
216209
"""
217-
if isinstance(cdecl, basestring):
210+
if isinstance(cdecl, str):
218211
cdecl = self._typeof(cdecl)
219212
return self._backend.alignof(cdecl)
220213

@@ -225,7 +218,7 @@ def offsetof(self, cdecl, *fields_or_indexes):
225218
You can also give numeric values which correspond to array
226219
items, in case of an array type.
227220
"""
228-
if isinstance(cdecl, basestring):
221+
if isinstance(cdecl, str):
229222
cdecl = self._typeof(cdecl)
230223
return self._typeoffsetof(cdecl, *fields_or_indexes)[1]
231224

@@ -252,7 +245,7 @@ def new(self, cdecl, init=None):
252245
about that when copying the pointer to the memory somewhere
253246
else, e.g. into another structure.
254247
"""
255-
if isinstance(cdecl, basestring):
248+
if isinstance(cdecl, str):
256249
cdecl = self._typeof(cdecl)
257250
return self._backend.newp(cdecl, init)
258251

@@ -275,7 +268,7 @@ def new_allocator(self, alloc=None, free=None,
275268
allocator = compiled_ffi.new_allocator(alloc, free,
276269
should_clear_after_alloc)
277270
def allocate(cdecl, init=None):
278-
if isinstance(cdecl, basestring):
271+
if isinstance(cdecl, str):
279272
cdecl = self._typeof(cdecl)
280273
return allocator(cdecl, init)
281274
return allocate
@@ -285,7 +278,7 @@ def cast(self, cdecl, source):
285278
type initialized with the given 'source'. The source is
286279
casted between integers or pointers of any type.
287280
"""
288-
if isinstance(cdecl, basestring):
281+
if isinstance(cdecl, str):
289282
cdecl = self._typeof(cdecl)
290283
return self._backend.cast(cdecl, source)
291284

@@ -350,7 +343,7 @@ def from_buffer(self, cdecl, python_buffer=_unspecified,
350343
"""
351344
if python_buffer is _unspecified:
352345
cdecl, python_buffer = self.BCharA, cdecl
353-
elif isinstance(cdecl, basestring):
346+
elif isinstance(cdecl, str):
354347
cdecl = self._typeof(cdecl)
355348
return self._backend.from_buffer(cdecl, python_buffer,
356349
require_writable)
@@ -385,7 +378,7 @@ def callback_decorator_wrap(python_callable):
385378
"is not callable")
386379
return self._backend.callback(cdecl, python_callable,
387380
error, onerror)
388-
if isinstance(cdecl, basestring):
381+
if isinstance(cdecl, str):
389382
cdecl = self._typeof(cdecl, consider_function_as_funcptr=True)
390383
if python_callable is None:
391384
return callback_decorator_wrap # decorator mode
@@ -398,7 +391,7 @@ def getctype(self, cdecl, replace_with=''):
398391
extra text to append (or insert for more complicated C types), like
399392
a variable name, or '*' to get actually the C type 'pointer-to-cdecl'.
400393
"""
401-
if isinstance(cdecl, basestring):
394+
if isinstance(cdecl, str):
402395
cdecl = self._typeof(cdecl)
403396
replace_with = replace_with.strip()
404397
if (replace_with.startswith('*')
@@ -605,10 +598,7 @@ def ensure(key, value):
605598
if hasattr(sys, 'gettotalrefcount'):
606599
template += '_d'
607600
else:
608-
try:
609-
import sysconfig
610-
except ImportError: # 2.6
611-
from cffi._shimmed_dist_utils import sysconfig
601+
import sysconfig
612602
template = "python%d.%d"
613603
if sysconfig.get_config_var('DEBUG_EXT'):
614604
template += sysconfig.get_config_var('DEBUG_EXT')
@@ -625,7 +615,7 @@ def set_source(self, module_name, source, source_extension='.c', **kwds):
625615
if hasattr(self, '_assigned_source'):
626616
raise ValueError("set_source() cannot be called several times "
627617
"per ffi object")
628-
if not isinstance(module_name, basestring):
618+
if not isinstance(module_name, str):
629619
raise TypeError("'module_name' must be a string")
630620
if os.sep in module_name or (os.altsep and os.altsep in module_name):
631621
raise ValueError("'module_name' must not contain '/': use a dotted "
@@ -791,7 +781,7 @@ def list_types(self):
791781

792782
def _load_backend_lib(backend, name, flags):
793783
import os
794-
if not isinstance(name, basestring):
784+
if not isinstance(name, str):
795785
if sys.platform != "win32" or name is not None:
796786
return backend.load_library(name, flags)
797787
name = "c" # Windows: load_library(None) fails, but this works
@@ -805,8 +795,8 @@ def _load_backend_lib(backend, name, flags):
805795
import ctypes.util
806796
path = ctypes.util.find_library(name)
807797
if path is None:
808-
if name == "c" and sys.platform == "win32" and sys.version_info >= (3,):
809-
raise OSError("dlopen(None) cannot work on Windows for Python 3 "
798+
if name == "c" and sys.platform == "win32":
799+
raise OSError("dlopen(None) cannot work on Windows "
810800
"(see http://bugs.python.org/issue23606)")
811801
msg = ("ctypes.util.find_library() did not manage "
812802
f"to locate a library called {name!r}")
@@ -927,7 +917,7 @@ def __cffi_close__(self):
927917
backendlib.close_lib()
928918
self.__dict__.clear()
929919
#
930-
if isinstance(libname, basestring):
920+
if isinstance(libname, str):
931921
try:
932922
if not isinstance(libname, str): # unicode, on Python 2
933923
libname = libname.encode('utf-8')

‎src/cffi/backend_ctypes.py‎

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
11
import ctypes, ctypes.util, operator, sys
22
from . import model
33

4-
unicode = str
5-
long = int
6-
xrange = range
7-
bytechr = lambda num: bytes([num])
8-
94
class CTypesType(type):
105
pass
116

@@ -154,7 +149,7 @@ def _newp(cls, init):
154149
return cls(init)
155150

156151
def __iter__(self):
157-
for i in xrange(len(self)):
152+
for i in range(len(self)):
158153
yield self[i]
159154

160155
def _get_own_repr(self):
@@ -176,7 +171,7 @@ def _cast_from(cls, source):
176171
address = 0
177172
elif isinstance(source, CTypesData):
178173
address = source._cast_to_integer()
179-
elif isinstance(source, (int, long)):
174+
elif isinstance(source, int):
180175
address = source
181176
else:
182177
raise TypeError(f"bad type for cast to {cls!r}: {type(source).__name__!r}")
@@ -348,7 +343,7 @@ def new_primitive_type(self, name):
348343
is_signed = (ctype(-1).value == -1)
349344
#
350345
def _cast_source_to_int(source):
351-
if isinstance(source, (int, long, float)):
346+
if isinstance(source, (int, float)):
352347
source = int(source)
353348
elif isinstance(source, CTypesData):
354349
source = source._cast_to_integer()
@@ -388,7 +383,7 @@ def __int__(self):
388383
if kind == 'bool':
389384
@classmethod
390385
def _cast_from(cls, source):
391-
if not isinstance(source, (int, long, float)):
386+
if not isinstance(source, (int, float)):
392387
source = _cast_source_to_int(source)
393388
return cls(bool(source))
394389
def __int__(self):
@@ -398,7 +393,7 @@ def __int__(self):
398393
@classmethod
399394
def _cast_from(cls, source):
400395
source = _cast_source_to_int(source)
401-
source = bytechr(source & 0xFF)
396+
source = bytes([source & 0xFF])
402397
return cls(source)
403398
def __int__(self):
404399
return ord(self._value)
@@ -427,7 +422,7 @@ def __float__(self):
427422
if kind in {'int', 'byte', 'bool'}:
428423
@staticmethod
429424
def _to_ctypes(x):
430-
if not isinstance(x, (int, long)):
425+
if not isinstance(x, int):
431426
if isinstance(x, CTypesData):
432427
x = int(x)
433428
else:
@@ -457,7 +452,7 @@ def __nonzero__(self):
457452
if kind == 'float':
458453
@staticmethod
459454
def _to_ctypes(x):
460-
if not isinstance(x, (int, long, float, CTypesData)):
455+
if not isinstance(x, (int, float, CTypesData)):
461456
raise TypeError(f"float expected, got {type(x).__name__}")
462457
return ctype(x).value
463458

@@ -520,14 +515,14 @@ def __init__(self, init):
520515
self._own = True
521516

522517
def __add__(self, other):
523-
if isinstance(other, (int, long)):
518+
if isinstance(other, int):
524519
return self._new_pointer_at(self._address +
525520
other * self._bitem_size)
526521
else:
527522
return NotImplemented
528523

529524
def __sub__(self, other):
530-
if isinstance(other, (int, long)):
525+
if isinstance(other, int):
531526
return self._new_pointer_at(self._address -
532527
other * self._bitem_size)
533528
elif type(self) is type(other):
@@ -602,7 +597,7 @@ class CTypesArray(CTypesGenericArray):
602597

603598
def __init__(self, init):
604599
if length is None:
605-
if isinstance(init, (int, long)):
600+
if isinstance(init, int):
606601
len1 = init
607602
init = None
608603
elif kind == 'char' and isinstance(init, bytes):
@@ -681,7 +676,7 @@ def _arg_to_ctypes(value):
681676
return CTypesPtr._arg_to_ctypes(value)
682677

683678
def __add__(self, other):
684-
if isinstance(other, (int, long)):
679+
if isinstance(other, int):
685680
return CTypesPtr._new_pointer_at(
686681
ctypes.addressof(self._blob) +
687682
other * ctypes.sizeof(BItem._ctype))
@@ -760,7 +755,7 @@ def initialize(blob, init):
760755
"only one supported (use a dict if needed)"
761756
% (len(init),))
762757
if not isinstance(init, dict):
763-
if isinstance(init, (bytes, unicode)):
758+
if isinstance(init, (bytes, str)):
764759
raise TypeError("union initializer: got a str")
765760
init = tuple(init)
766761
if len(init) > len(fnames):
@@ -1044,7 +1039,7 @@ def typeoffsetof(self, BType, fieldname, num=0):
10441039
if BField is Ellipsis:
10451040
raise TypeError("not supported for bitfields")
10461041
return (BField, BType._offsetof(fieldname))
1047-
elif isinstance(fieldname, (int, long)):
1042+
elif isinstance(fieldname, int):
10481043
if issubclass(BType, CTypesGenericArray):
10491044
BType = BType._CTPtr
10501045
if not issubclass(BType, CTypesGenericPtr):

‎src/cffi/ffiplatform.py‎

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import sys, os
1+
import sys, os, io
22
from .error import VerificationError
33

44

@@ -81,13 +81,6 @@ def maybe_relative_path(path):
8181

8282
# ____________________________________________________________
8383

84-
try:
85-
int_or_long = (int, long)
86-
import cStringIO
87-
except NameError:
88-
int_or_long = int # Python 3
89-
import io as cStringIO
90-
9184
def _flatten(x, f):
9285
if isinstance(x, str):
9386
f.write('%ds%s' % (len(x), x))
@@ -101,13 +94,13 @@ def _flatten(x, f):
10194
f.write('%dl' % len(x))
10295
for value in x:
10396
_flatten(value, f)
104-
elif isinstance(x, int_or_long):
97+
elif isinstance(x, int):
10598
f.write('%di' % (x,))
10699
else:
107100
raise TypeError(
108101
f"the keywords to verify() contains unsupported object {x!r}")
109102

110103
def flatten(x):
111-
f = cStringIO.StringIO()
104+
f = io.StringIO()
112105
_flatten(x, f)
113106
return f.getvalue()

‎src/cffi/lock.py‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
import sys
22

3-
try:
4-
from _thread import allocate_lock
5-
except ImportError:
6-
from _dummy_thread import allocate_lock
3+
from _thread import allocate_lock
74

85

96
##import sys

‎src/cffi/pkgconfig.py‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,11 @@ def call(libname, flag, encoding=sys.getfilesystemencoding()):
4242
pass
4343
raise PkgConfigError(berr.strip())
4444

45-
if sys.version_info >= (3,) and not isinstance(bout, str): # Python 3.x
46-
try:
47-
bout = bout.decode(encoding)
48-
except UnicodeDecodeError:
49-
raise PkgConfigError(f"pkg-config {flag} {libname} returned bytes that cannot "
50-
f"be decoded with encoding {encoding!r}:\n{bout!r}")
45+
try:
46+
bout = bout.decode(encoding)
47+
except UnicodeDecodeError:
48+
raise PkgConfigError(f"pkg-config {flag} {libname} returned bytes that cannot "
49+
f"be decoded with encoding {encoding!r}:\n{bout!r}")
5150

5251
if os.altsep != '\\' and '\\' in bout:
5352
raise PkgConfigError(f"pkg-config {flag} {libname} returned an unsupported "

0 commit comments

Comments
 (0)