Skip to content

Commit 91bd477

Browse files
Apply ruff/pyupgrade rule UP036
UP036 Version block is outdated for minimum Python version Lots of manual fixes here, in order to discard Python 2 aliases. Co-authored-by: Matti Picus <[email protected]>
1 parent 2c33676 commit 91bd477

18 files changed

+199
-371
lines changed

src/c/test_c.py

Lines changed: 126 additions & 189 deletions
Large diffs are not rendered by default.

src/cffi/api.py

Lines changed: 16 additions & 25 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('*')
@@ -596,10 +590,7 @@ def ensure(key, value):
596590
# we need 'libpypy-c.{so,dylib}', which should be by
597591
# default located in 'sys.prefix/bin' for installed
598592
# systems.
599-
if sys.version_info < (3,):
600-
pythonlib = "pypy-c"
601-
else:
602-
pythonlib = "pypy3-c"
593+
pythonlib = "pypy3-c"
603594
if hasattr(sys, 'prefix'):
604595
ensure('library_dirs', os.path.join(sys.prefix, 'bin'))
605596
# On uninstalled pypy's, the libpypy-c is typically found in
@@ -632,7 +623,7 @@ def set_source(self, module_name, source, source_extension='.c', **kwds):
632623
if hasattr(self, '_assigned_source'):
633624
raise ValueError("set_source() cannot be called several times "
634625
"per ffi object")
635-
if not isinstance(module_name, basestring):
626+
if not isinstance(module_name, str):
636627
raise TypeError("'module_name' must be a string")
637628
if os.sep in module_name or (os.altsep and os.altsep in module_name):
638629
raise ValueError("'module_name' must not contain '/': use a dotted "
@@ -798,7 +789,7 @@ def list_types(self):
798789

799790
def _load_backend_lib(backend, name, flags):
800791
import os
801-
if not isinstance(name, basestring):
792+
if not isinstance(name, str):
802793
if sys.platform != "win32" or name is not None:
803794
return backend.load_library(name, flags)
804795
name = "c" # Windows: load_library(None) fails, but this works
@@ -934,7 +925,7 @@ def __cffi_close__(self):
934925
backendlib.close_lib()
935926
self.__dict__.clear()
936927
#
937-
if isinstance(libname, basestring):
928+
if isinstance(libname, str):
938929
try:
939930
if not isinstance(libname, str): # unicode, on Python 2
940931
libname = libname.encode('utf-8')

src/cffi/backend_ctypes.py

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

4-
if sys.version_info < (3,):
5-
bytechr = chr
6-
else:
7-
unicode = str
8-
long = int
9-
xrange = range
10-
bytechr = lambda num: bytes([num])
11-
124
class CTypesType(type):
135
pass
146

@@ -161,7 +153,7 @@ def _newp(cls, init):
161153
return cls(init)
162154

163155
def __iter__(self):
164-
for i in xrange(len(self)):
156+
for i in range(len(self)):
165157
yield self[i]
166158

167159
def _get_own_repr(self):
@@ -183,7 +175,7 @@ def _cast_from(cls, source):
183175
address = 0
184176
elif isinstance(source, CTypesData):
185177
address = source._cast_to_integer()
186-
elif isinstance(source, (int, long)):
178+
elif isinstance(source, int):
187179
address = source
188180
else:
189181
raise TypeError("bad type for cast to %r: %r" %
@@ -399,7 +391,7 @@ def __int__(self):
399391
if kind == 'bool':
400392
@classmethod
401393
def _cast_from(cls, source):
402-
if not isinstance(source, (int, long, float)):
394+
if not isinstance(source, (int, float)):
403395
source = _cast_source_to_int(source)
404396
return cls(bool(source))
405397
def __int__(self):
@@ -409,7 +401,7 @@ def __int__(self):
409401
@classmethod
410402
def _cast_from(cls, source):
411403
source = _cast_source_to_int(source)
412-
source = bytechr(source & 0xFF)
404+
source = bytes([source & 0xFF])
413405
return cls(source)
414406
def __int__(self):
415407
return ord(self._value)
@@ -438,7 +430,7 @@ def __float__(self):
438430
if kind == 'int' or kind == 'byte' or kind == 'bool':
439431
@staticmethod
440432
def _to_ctypes(x):
441-
if not isinstance(x, (int, long)):
433+
if not isinstance(x, int):
442434
if isinstance(x, CTypesData):
443435
x = int(x)
444436
else:
@@ -471,7 +463,7 @@ def __nonzero__(self):
471463
if kind == 'float':
472464
@staticmethod
473465
def _to_ctypes(x):
474-
if not isinstance(x, (int, long, float, CTypesData)):
466+
if not isinstance(x, (int, float, CTypesData)):
475467
raise TypeError("float expected, got %s" %
476468
type(x).__name__)
477469
return ctype(x).value
@@ -535,14 +527,14 @@ def __init__(self, init):
535527
self._own = True
536528

537529
def __add__(self, other):
538-
if isinstance(other, (int, long)):
530+
if isinstance(other, int):
539531
return self._new_pointer_at(self._address +
540532
other * self._bitem_size)
541533
else:
542534
return NotImplemented
543535

544536
def __sub__(self, other):
545-
if isinstance(other, (int, long)):
537+
if isinstance(other, int):
546538
return self._new_pointer_at(self._address -
547539
other * self._bitem_size)
548540
elif type(self) is type(other):
@@ -617,7 +609,7 @@ class CTypesArray(CTypesGenericArray):
617609

618610
def __init__(self, init):
619611
if length is None:
620-
if isinstance(init, (int, long)):
612+
if isinstance(init, int):
621613
len1 = init
622614
init = None
623615
elif kind == 'char' and isinstance(init, bytes):
@@ -696,7 +688,7 @@ def _arg_to_ctypes(value):
696688
return CTypesPtr._arg_to_ctypes(value)
697689

698690
def __add__(self, other):
699-
if isinstance(other, (int, long)):
691+
if isinstance(other, long):
700692
return CTypesPtr._new_pointer_at(
701693
ctypes.addressof(self._blob) +
702694
other * ctypes.sizeof(BItem._ctype))
@@ -776,7 +768,7 @@ def initialize(blob, init):
776768
"only one supported (use a dict if needed)"
777769
% (len(init),))
778770
if not isinstance(init, dict):
779-
if isinstance(init, (bytes, unicode)):
771+
if isinstance(init, (bytes, str)):
780772
raise TypeError("union initializer: got a str")
781773
init = tuple(init)
782774
if len(init) > len(fnames):
@@ -1061,7 +1053,7 @@ def typeoffsetof(self, BType, fieldname, num=0):
10611053
if BField is Ellipsis:
10621054
raise TypeError("not supported for bitfields")
10631055
return (BField, BType._offsetof(fieldname))
1064-
elif isinstance(fieldname, (int, long)):
1056+
elif isinstance(fieldname, int):
10651057
if issubclass(BType, CTypesGenericArray):
10661058
BType = BType._CTPtr
10671059
if not issubclass(BType, CTypesGenericPtr):

src/cffi/cparser.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,7 @@
88
import weakref, re, sys
99

1010
try:
11-
if sys.version_info < (3,):
12-
import thread as _thread
13-
else:
14-
import _thread
11+
import _thread
1512
lock = _thread.allocate_lock()
1613
except ImportError:
1714
lock = None

src/cffi/lock.py

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

3-
if sys.version_info < (3,):
4-
try:
5-
from thread import allocate_lock
6-
except ImportError:
7-
from dummy_thread import allocate_lock
8-
else:
9-
try:
10-
from _thread import allocate_lock
11-
except ImportError:
12-
from _dummy_thread import allocate_lock
3+
try:
4+
from _thread import allocate_lock
5+
except ImportError:
6+
from _dummy_thread import allocate_lock
137

148

159
##import sys

src/cffi/recompiler.py

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1316,12 +1316,8 @@ def _print_string_literal_in_array(self, s):
13161316
else:
13171317
s.decode('utf-8') # got bytes, check for valid utf-8
13181318
for line in s.splitlines(True):
1319-
comment = line
1320-
if type('//') is bytes: # python2
1321-
line = map(ord, line) # make a list of integers
1322-
else: # python3
1323-
# type(line) is bytes, which enumerates like a list of integers
1324-
comment = ascii(comment)[1:-1]
1319+
# type(line) is bytes, which enumerates like a list of integers
1320+
comment = ascii(line)[1:-1]
13251321
prnt(('// ' + comment).rstrip())
13261322
printed_line = ''
13271323
for c in line:
@@ -1406,15 +1402,6 @@ def _emit_bytecode_EnumType(self, tp, index):
14061402
self.cffi_types[index] = CffiOp(OP_ENUM, enum_index)
14071403

14081404

1409-
if sys.version_info >= (3,):
1410-
NativeIO = io.StringIO
1411-
else:
1412-
class NativeIO(io.BytesIO):
1413-
def write(self, s):
1414-
if isinstance(s, unicode):
1415-
s = s.encode('ascii')
1416-
super().write(s)
1417-
14181405
def _is_file_like(maybefile):
14191406
# compare to xml.etree.ElementTree._get_writer
14201407
return hasattr(maybefile, 'write')
@@ -1429,7 +1416,7 @@ def _make_c_or_py_source(ffi, module_name, preamble, target_file, verbose):
14291416
if _is_file_like(target_file):
14301417
recompiler.write_source_to_f(target_file, preamble)
14311418
return True
1432-
f = NativeIO()
1419+
f = io.StringIO()
14331420
recompiler.write_source_to_f(f, preamble)
14341421
output = f.getvalue()
14351422
try:

src/cffi/vengine_gen.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -55,12 +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-
if sys.version_info >= (3,):
59-
prefix = 'PyInit_'
60-
else:
61-
prefix = 'init'
6258
modname = self.verifier.get_module_name()
63-
prnt("void %s%s(void) { }\n" % (prefix, modname))
59+
prnt(f"void PyInit_{modname}(void) { }\n")
6460

6561
def load_library(self, flags=0):
6662
# import it with the CFFI backend
@@ -496,10 +492,7 @@ def _load_known_int_constant(self, module, funcname):
496492
function = module.load_function(BFunc, funcname)
497493
p = self.ffi.new(BType, 256)
498494
if function(p) < 0:
499-
error = self.ffi.string(p)
500-
if sys.version_info >= (3,):
501-
error = str(error, 'utf-8')
502-
raise VerificationError(error)
495+
raise VerificationError(self.ffi.string(p))
503496

504497
def _enum_funcname(self, prefix, name):
505498
# "$enum_$1" => "___D_enum____D_1"

0 commit comments

Comments
 (0)