Skip to content

Commit 265f863

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 728919b commit 265f863

9 files changed

Lines changed: 49 additions & 90 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__:
@@ -111,7 +104,7 @@ def embedding_api(self, csource, packed=False, pack=None):
111104

112105
def _cdef(self, csource, override=False, **options):
113106
if not isinstance(csource, str): # unicode, on Python 2
114-
if not isinstance(csource, basestring):
107+
if not isinstance(csource, str):
115108
raise TypeError("cdef() argument must be a string")
116109
csource = csource.encode('ascii')
117110
with self._lock:
@@ -134,7 +127,7 @@ def dlopen(self, name, flags=0):
134127
linked to a particular library, just like C headers; in the
135128
library we only look for the actual (untyped) symbols.
136129
"""
137-
if not (isinstance(name, basestring) or
130+
if not (isinstance(name, str) or
138131
name is None or
139132
isinstance(name, self.CData)):
140133
raise TypeError("dlopen(name): name must be a file name, None, "
@@ -189,7 +182,7 @@ def typeof(self, cdecl):
189182
corresponding <ctype> object.
190183
It can also be used on 'cdata' instance to get its C type.
191184
"""
192-
if isinstance(cdecl, basestring):
185+
if isinstance(cdecl, str):
193186
return self._typeof(cdecl)
194187
if isinstance(cdecl, self.CData):
195188
return self._backend.typeof(cdecl)
@@ -207,7 +200,7 @@ def sizeof(self, cdecl):
207200
"""Return the size in bytes of the argument. It can be a
208201
string naming a C type, or a 'cdata' instance.
209202
"""
210-
if isinstance(cdecl, basestring):
203+
if isinstance(cdecl, str):
211204
BType = self._typeof(cdecl)
212205
return self._backend.sizeof(BType)
213206
else:
@@ -217,7 +210,7 @@ def alignof(self, cdecl):
217210
"""Return the natural alignment size in bytes of the C type
218211
given as a string.
219212
"""
220-
if isinstance(cdecl, basestring):
213+
if isinstance(cdecl, str):
221214
cdecl = self._typeof(cdecl)
222215
return self._backend.alignof(cdecl)
223216

@@ -228,7 +221,7 @@ def offsetof(self, cdecl, *fields_or_indexes):
228221
You can also give numeric values which correspond to array
229222
items, in case of an array type.
230223
"""
231-
if isinstance(cdecl, basestring):
224+
if isinstance(cdecl, str):
232225
cdecl = self._typeof(cdecl)
233226
return self._typeoffsetof(cdecl, *fields_or_indexes)[1]
234227

@@ -255,7 +248,7 @@ def new(self, cdecl, init=None):
255248
about that when copying the pointer to the memory somewhere
256249
else, e.g. into another structure.
257250
"""
258-
if isinstance(cdecl, basestring):
251+
if isinstance(cdecl, str):
259252
cdecl = self._typeof(cdecl)
260253
return self._backend.newp(cdecl, init)
261254

@@ -278,7 +271,7 @@ def new_allocator(self, alloc=None, free=None,
278271
allocator = compiled_ffi.new_allocator(alloc, free,
279272
should_clear_after_alloc)
280273
def allocate(cdecl, init=None):
281-
if isinstance(cdecl, basestring):
274+
if isinstance(cdecl, str):
282275
cdecl = self._typeof(cdecl)
283276
return allocator(cdecl, init)
284277
return allocate
@@ -288,7 +281,7 @@ def cast(self, cdecl, source):
288281
type initialized with the given 'source'. The source is
289282
casted between integers or pointers of any type.
290283
"""
291-
if isinstance(cdecl, basestring):
284+
if isinstance(cdecl, str):
292285
cdecl = self._typeof(cdecl)
293286
return self._backend.cast(cdecl, source)
294287

@@ -353,7 +346,7 @@ def from_buffer(self, cdecl, python_buffer=_unspecified,
353346
"""
354347
if python_buffer is _unspecified:
355348
cdecl, python_buffer = self.BCharA, cdecl
356-
elif isinstance(cdecl, basestring):
349+
elif isinstance(cdecl, str):
357350
cdecl = self._typeof(cdecl)
358351
return self._backend.from_buffer(cdecl, python_buffer,
359352
require_writable)
@@ -388,7 +381,7 @@ def callback_decorator_wrap(python_callable):
388381
"is not callable")
389382
return self._backend.callback(cdecl, python_callable,
390383
error, onerror)
391-
if isinstance(cdecl, basestring):
384+
if isinstance(cdecl, str):
392385
cdecl = self._typeof(cdecl, consider_function_as_funcptr=True)
393386
if python_callable is None:
394387
return callback_decorator_wrap # decorator mode
@@ -401,7 +394,7 @@ def getctype(self, cdecl, replace_with=''):
401394
extra text to append (or insert for more complicated C types), like
402395
a variable name, or '*' to get actually the C type 'pointer-to-cdecl'.
403396
"""
404-
if isinstance(cdecl, basestring):
397+
if isinstance(cdecl, str):
405398
cdecl = self._typeof(cdecl)
406399
replace_with = replace_with.strip()
407400
if (replace_with.startswith('*')
@@ -609,10 +602,7 @@ def ensure(key, value):
609602
if hasattr(sys, 'gettotalrefcount'):
610603
template += '_d'
611604
else:
612-
try:
613-
import sysconfig
614-
except ImportError: # 2.6
615-
from cffi._shimmed_dist_utils import sysconfig
605+
import sysconfig
616606
template = "python%d.%d"
617607
if sysconfig.get_config_var('DEBUG_EXT'):
618608
template += sysconfig.get_config_var('DEBUG_EXT')
@@ -629,7 +619,7 @@ def set_source(self, module_name, source, source_extension='.c', **kwds):
629619
if hasattr(self, '_assigned_source'):
630620
raise ValueError("set_source() cannot be called several times "
631621
"per ffi object")
632-
if not isinstance(module_name, basestring):
622+
if not isinstance(module_name, str):
633623
raise TypeError("'module_name' must be a string")
634624
if os.sep in module_name or (os.altsep and os.altsep in module_name):
635625
raise ValueError("'module_name' must not contain '/': use a dotted "
@@ -795,7 +785,7 @@ def list_types(self):
795785

796786
def _load_backend_lib(backend, name, flags):
797787
import os
798-
if not isinstance(name, basestring):
788+
if not isinstance(name, str):
799789
if sys.platform != "win32" or name is not None:
800790
return backend.load_library(name, flags)
801791
name = "c" # Windows: load_library(None) fails, but this works
@@ -809,8 +799,8 @@ def _load_backend_lib(backend, name, flags):
809799
import ctypes.util
810800
path = ctypes.util.find_library(name)
811801
if path is None:
812-
if name == "c" and sys.platform == "win32" and sys.version_info >= (3,):
813-
raise OSError("dlopen(None) cannot work on Windows for Python 3 "
802+
if name == "c" and sys.platform == "win32":
803+
raise OSError("dlopen(None) cannot work on Windows "
814804
"(see http://bugs.python.org/issue23606)")
815805
msg = ("ctypes.util.find_library() did not manage "
816806
"to locate a library called %r" % (name,))
@@ -931,7 +921,7 @@ def __cffi_close__(self):
931921
backendlib.close_lib()
932922
self.__dict__.clear()
933923
#
934-
if isinstance(libname, basestring):
924+
if isinstance(libname, str):
935925
try:
936926
if not isinstance(libname, str): # unicode, on Python 2
937927
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

@@ -158,7 +153,7 @@ def _newp(cls, init):
158153
return cls(init)
159154

160155
def __iter__(self):
161-
for i in xrange(len(self)):
156+
for i in range(len(self)):
162157
yield self[i]
163158

164159
def _get_own_repr(self):
@@ -180,7 +175,7 @@ def _cast_from(cls, source):
180175
address = 0
181176
elif isinstance(source, CTypesData):
182177
address = source._cast_to_integer()
183-
elif isinstance(source, (int, long)):
178+
elif isinstance(source, int):
184179
address = source
185180
else:
186181
raise TypeError("bad type for cast to %r: %r" %
@@ -354,7 +349,7 @@ def new_primitive_type(self, name):
354349
is_signed = (ctype(-1).value == -1)
355350
#
356351
def _cast_source_to_int(source):
357-
if isinstance(source, (int, long, float)):
352+
if isinstance(source, (int, float)):
358353
source = int(source)
359354
elif isinstance(source, CTypesData):
360355
source = source._cast_to_integer()
@@ -395,7 +390,7 @@ def __int__(self):
395390
if kind == 'bool':
396391
@classmethod
397392
def _cast_from(cls, source):
398-
if not isinstance(source, (int, long, float)):
393+
if not isinstance(source, (int, float)):
399394
source = _cast_source_to_int(source)
400395
return cls(bool(source))
401396
def __int__(self):
@@ -405,7 +400,7 @@ def __int__(self):
405400
@classmethod
406401
def _cast_from(cls, source):
407402
source = _cast_source_to_int(source)
408-
source = bytechr(source & 0xFF)
403+
source = bytes([source & 0xFF])
409404
return cls(source)
410405
def __int__(self):
411406
return ord(self._value)
@@ -434,7 +429,7 @@ def __float__(self):
434429
if kind in {'int', 'byte', 'bool'}:
435430
@staticmethod
436431
def _to_ctypes(x):
437-
if not isinstance(x, (int, long)):
432+
if not isinstance(x, int):
438433
if isinstance(x, CTypesData):
439434
x = int(x)
440435
else:
@@ -467,7 +462,7 @@ def __nonzero__(self):
467462
if kind == 'float':
468463
@staticmethod
469464
def _to_ctypes(x):
470-
if not isinstance(x, (int, long, float, CTypesData)):
465+
if not isinstance(x, (int, float, CTypesData)):
471466
raise TypeError("float expected, got %s" %
472467
type(x).__name__)
473468
return ctype(x).value
@@ -531,14 +526,14 @@ def __init__(self, init):
531526
self._own = True
532527

533528
def __add__(self, other):
534-
if isinstance(other, (int, long)):
529+
if isinstance(other, int):
535530
return self._new_pointer_at(self._address +
536531
other * self._bitem_size)
537532
else:
538533
return NotImplemented
539534

540535
def __sub__(self, other):
541-
if isinstance(other, (int, long)):
536+
if isinstance(other, int):
542537
return self._new_pointer_at(self._address -
543538
other * self._bitem_size)
544539
elif type(self) is type(other):
@@ -613,7 +608,7 @@ class CTypesArray(CTypesGenericArray):
613608

614609
def __init__(self, init):
615610
if length is None:
616-
if isinstance(init, (int, long)):
611+
if isinstance(init, int):
617612
len1 = init
618613
init = None
619614
elif kind == 'char' and isinstance(init, bytes):
@@ -692,7 +687,7 @@ def _arg_to_ctypes(value):
692687
return CTypesPtr._arg_to_ctypes(value)
693688

694689
def __add__(self, other):
695-
if isinstance(other, (int, long)):
690+
if isinstance(other, int):
696691
return CTypesPtr._new_pointer_at(
697692
ctypes.addressof(self._blob) +
698693
other * ctypes.sizeof(BItem._ctype))
@@ -772,7 +767,7 @@ def initialize(blob, init):
772767
"only one supported (use a dict if needed)"
773768
% (len(init),))
774769
if not isinstance(init, dict):
775-
if isinstance(init, (bytes, unicode)):
770+
if isinstance(init, (bytes, str)):
776771
raise TypeError("union initializer: got a str")
777772
init = tuple(init)
778773
if len(init) > len(fnames):
@@ -1057,7 +1052,7 @@ def typeoffsetof(self, BType, fieldname, num=0):
10571052
if BField is Ellipsis:
10581053
raise TypeError("not supported for bitfields")
10591054
return (BField, BType._offsetof(fieldname))
1060-
elif isinstance(fieldname, (int, long)):
1055+
elif isinstance(fieldname, int):
10611056
if issubclass(BType, CTypesGenericArray):
10621057
BType = BType._CTPtr
10631058
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
"the keywords to verify() contains unsupported object %r" % (x,))
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: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,12 @@ 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("pkg-config %s %s returned bytes that cannot "
50-
"be decoded with encoding %r:\n%r" %
51-
(flag, libname, encoding, bout))
45+
try:
46+
bout = bout.decode(encoding)
47+
except UnicodeDecodeError:
48+
raise PkgConfigError("pkg-config %s %s returned bytes that cannot "
49+
"be decoded with encoding %r:\n%r" %
50+
(flag, libname, encoding, bout))
5251

5352
if os.altsep != '\\' and '\\' in bout:
5453
raise PkgConfigError("pkg-config %s %s returned an unsupported "

0 commit comments

Comments
 (0)