Skip to content

Commit 2de1e2b

Browse files
Remove outdated Python pre-3.9 code
These are manual fixes
1 parent f2d4d69 commit 2de1e2b

22 files changed

Lines changed: 356 additions & 503 deletions

‎src/c/test_c.py‎

Lines changed: 116 additions & 164 deletions
Large diffs are not rendered by default.

‎src/cffi/api.py‎

Lines changed: 15 additions & 21 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

@@ -111,7 +105,7 @@ def embedding_api(self, csource, packed=False, pack=None):
111105

112106
def _cdef(self, csource, override=False, **options):
113107
if not isinstance(csource, str): # unicode, on Python 2
114-
if not isinstance(csource, basestring):
108+
if not isinstance(csource, str):
115109
raise TypeError("cdef() argument must be a string")
116110
csource = csource.encode('ascii')
117111
with self._lock:
@@ -134,7 +128,7 @@ def dlopen(self, name, flags=0):
134128
linked to a particular library, just like C headers; in the
135129
library we only look for the actual (untyped) symbols.
136130
"""
137-
if not (isinstance(name, basestring) or
131+
if not (isinstance(name, str) or
138132
name is None or
139133
isinstance(name, self.CData)):
140134
raise TypeError("dlopen(name): name must be a file name, None, "
@@ -189,7 +183,7 @@ def typeof(self, cdecl):
189183
corresponding <ctype> object.
190184
It can also be used on 'cdata' instance to get its C type.
191185
"""
192-
if isinstance(cdecl, basestring):
186+
if isinstance(cdecl, str):
193187
return self._typeof(cdecl)
194188
if isinstance(cdecl, self.CData):
195189
return self._backend.typeof(cdecl)
@@ -207,7 +201,7 @@ def sizeof(self, cdecl):
207201
"""Return the size in bytes of the argument. It can be a
208202
string naming a C type, or a 'cdata' instance.
209203
"""
210-
if isinstance(cdecl, basestring):
204+
if isinstance(cdecl, str):
211205
BType = self._typeof(cdecl)
212206
return self._backend.sizeof(BType)
213207
else:
@@ -217,7 +211,7 @@ def alignof(self, cdecl):
217211
"""Return the natural alignment size in bytes of the C type
218212
given as a string.
219213
"""
220-
if isinstance(cdecl, basestring):
214+
if isinstance(cdecl, str):
221215
cdecl = self._typeof(cdecl)
222216
return self._backend.alignof(cdecl)
223217

@@ -228,7 +222,7 @@ def offsetof(self, cdecl, *fields_or_indexes):
228222
You can also give numeric values which correspond to array
229223
items, in case of an array type.
230224
"""
231-
if isinstance(cdecl, basestring):
225+
if isinstance(cdecl, str):
232226
cdecl = self._typeof(cdecl)
233227
return self._typeoffsetof(cdecl, *fields_or_indexes)[1]
234228

@@ -255,7 +249,7 @@ def new(self, cdecl, init=None):
255249
about that when copying the pointer to the memory somewhere
256250
else, e.g. into another structure.
257251
"""
258-
if isinstance(cdecl, basestring):
252+
if isinstance(cdecl, str):
259253
cdecl = self._typeof(cdecl)
260254
return self._backend.newp(cdecl, init)
261255

@@ -278,7 +272,7 @@ def new_allocator(self, alloc=None, free=None,
278272
allocator = compiled_ffi.new_allocator(alloc, free,
279273
should_clear_after_alloc)
280274
def allocate(cdecl, init=None):
281-
if isinstance(cdecl, basestring):
275+
if isinstance(cdecl, str):
282276
cdecl = self._typeof(cdecl)
283277
return allocator(cdecl, init)
284278
return allocate
@@ -288,7 +282,7 @@ def cast(self, cdecl, source):
288282
type initialized with the given 'source'. The source is
289283
casted between integers or pointers of any type.
290284
"""
291-
if isinstance(cdecl, basestring):
285+
if isinstance(cdecl, str):
292286
cdecl = self._typeof(cdecl)
293287
return self._backend.cast(cdecl, source)
294288

@@ -353,7 +347,7 @@ def from_buffer(self, cdecl, python_buffer=_unspecified,
353347
"""
354348
if python_buffer is _unspecified:
355349
cdecl, python_buffer = self.BCharA, cdecl
356-
elif isinstance(cdecl, basestring):
350+
elif isinstance(cdecl, str):
357351
cdecl = self._typeof(cdecl)
358352
return self._backend.from_buffer(cdecl, python_buffer,
359353
require_writable)
@@ -388,7 +382,7 @@ def callback_decorator_wrap(python_callable):
388382
"is not callable")
389383
return self._backend.callback(cdecl, python_callable,
390384
error, onerror)
391-
if isinstance(cdecl, basestring):
385+
if isinstance(cdecl, str):
392386
cdecl = self._typeof(cdecl, consider_function_as_funcptr=True)
393387
if python_callable is None:
394388
return callback_decorator_wrap # decorator mode
@@ -401,7 +395,7 @@ def getctype(self, cdecl, replace_with=''):
401395
extra text to append (or insert for more complicated C types), like
402396
a variable name, or '*' to get actually the C type 'pointer-to-cdecl'.
403397
"""
404-
if isinstance(cdecl, basestring):
398+
if isinstance(cdecl, str):
405399
cdecl = self._typeof(cdecl)
406400
replace_with = replace_with.strip()
407401
if (replace_with.startswith('*')
@@ -629,7 +623,7 @@ def set_source(self, module_name, source, source_extension='.c', **kwds):
629623
if hasattr(self, '_assigned_source'):
630624
raise ValueError("set_source() cannot be called several times "
631625
"per ffi object")
632-
if not isinstance(module_name, basestring):
626+
if not isinstance(module_name, str):
633627
raise TypeError("'module_name' must be a string")
634628
if os.sep in module_name or (os.altsep and os.altsep in module_name):
635629
raise ValueError("'module_name' must not contain '/': use a dotted "
@@ -795,7 +789,7 @@ def list_types(self):
795789

796790
def _load_backend_lib(backend, name, flags):
797791
import os
798-
if not isinstance(name, basestring):
792+
if not isinstance(name, str):
799793
if sys.platform != "win32" or name is not None:
800794
return backend.load_library(name, flags)
801795
name = "c" # Windows: load_library(None) fails, but this works
@@ -931,7 +925,7 @@ def __cffi_close__(self):
931925
backendlib.close_lib()
932926
self.__dict__.clear()
933927
#
934-
if isinstance(libname, basestring):
928+
if isinstance(libname, str):
935929
try:
936930
if not isinstance(libname, str): # unicode, on Python 2
937931
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 & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import io
12
import sys, os
23
from .error import VerificationError
34

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

8283
# ____________________________________________________________
8384

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-
9185
def _flatten(x, f):
9286
if isinstance(x, str):
9387
f.write('%ds%s' % (len(x), x))
@@ -101,13 +95,13 @@ def _flatten(x, f):
10195
f.write('%dl' % len(x))
10296
for value in x:
10397
_flatten(value, f)
104-
elif isinstance(x, int_or_long):
98+
elif isinstance(x, int):
10599
f.write('%di' % (x,))
106100
else:
107101
raise TypeError(
108102
"the keywords to verify() contains unsupported object %r" % (x,))
109103

110104
def flatten(x):
111-
f = cStringIO.StringIO()
105+
f = io.StringIO()
112106
_flatten(x, f)
113107
return f.getvalue()

‎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 "

‎src/cffi/recompiler.py‎

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,8 @@
88
VERSION_CHAR16CHAR32 = 0x2801
99

1010
FREE_THREADED_BUILD = sysconfig.get_config_var("Py_GIL_DISABLED")
11-
USE_LIMITED_API = ((sys.platform != 'win32' or sys.version_info < (3, 0) or
12-
sys.version_info >= (3, 5)) and
13-
# free-threaded build doesn't support the stable ABI until Python 3.15
14-
(not FREE_THREADED_BUILD or sys.version_info >= (3, 15)))
11+
# free-threaded build doesn't support the stable ABI until Python 3.15
12+
USE_LIMITED_API = not FREE_THREADED_BUILD or sys.version_info >= (3, 15)
1513

1614
class GlobalExpr:
1715
def __init__(self, name, address, type_op, size=0, check_value=0):
@@ -1309,11 +1307,8 @@ def _print_string_literal_in_array(self, s):
13091307
s.decode('utf-8') # got bytes, check for valid utf-8
13101308
for line in s.splitlines(True):
13111309
comment = line
1312-
if type('//') is bytes: # python2
1313-
line = map(ord, line) # make a list of integers
1314-
else: # python3
1315-
# type(line) is bytes, which enumerates like a list of integers
1316-
comment = ascii(comment)[1:-1]
1310+
# type(line) is bytes, which enumerates like a list of integers
1311+
comment = ascii(comment)[1:-1]
13171312
prnt(('// ' + comment).rstrip())
13181313
printed_line = ''
13191314
for c in line:
@@ -1398,8 +1393,6 @@ def _emit_bytecode_EnumType(self, tp, index):
13981393
self.cffi_types[index] = CffiOp(OP_ENUM, enum_index)
13991394

14001395

1401-
NativeIO = io.StringIO
1402-
14031396
def _is_file_like(maybefile):
14041397
# compare to xml.etree.ElementTree._get_writer
14051398
return hasattr(maybefile, 'write')
@@ -1414,7 +1407,7 @@ def _make_c_or_py_source(ffi, module_name, preamble, target_file, verbose):
14141407
if _is_file_like(target_file):
14151408
recompiler.write_source_to_f(target_file, preamble)
14161409
return True
1417-
f = NativeIO()
1410+
f = io.StringIO()
14181411
recompiler.write_source_to_f(f, preamble)
14191412
output = f.getvalue()
14201413
try:

‎src/cffi/vengine_gen.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,8 @@ def write_source_to_f(self):
5555
# 'export_symbols', so instead of fighting it, just give up and
5656
# give it one
5757
if sys.platform == 'win32':
58-
prefix = 'PyInit_'
5958
modname = self.verifier.get_module_name()
60-
prnt("void %s%s(void) { }\n" % (prefix, modname))
59+
prnt(f"void PyInit_{modname}(void) {{ }}\n")
6160

6261
def load_library(self, flags=0):
6362
# import it with the CFFI backend

‎src/cffi/verifier.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ def _write_source(self, file=None):
161161
self._write_source_to(file)
162162
else:
163163
# Write our source file to an in memory file.
164-
f = NativeIO()
164+
f = io.StringIO()
165165
self._write_source_to(f)
166166
source_data = f.getvalue()
167167

0 commit comments

Comments
 (0)