Skip to content

Commit 07f386b

Browse files
Apply ruff/pyupgrade rules UP031 and UP032 (#261)
* Apply ruff/pyupgrade rules UP031 and UP032 These are automatic fixes using: * `--select UP031 --fix --unsafe-fixes` * `--select UP032 --fix` * Apply ruff/pyupgrade rule UP031 These are manual fixes
1 parent 1285f46 commit 07f386b

49 files changed

Lines changed: 641 additions & 736 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎demo/_curses.py‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def _check_ERR(code, fname):
9797
elif fname is None:
9898
raise error("curses function returned ERR")
9999
else:
100-
raise error("%s() returned ERR" % (fname,))
100+
raise error(f"{fname}() returned ERR")
101101

102102

103103
def _check_NULL(rval):
@@ -174,8 +174,7 @@ def _texttype(text):
174174
elif isinstance(text, unicode):
175175
return str(text) # default encoding
176176
else:
177-
raise TypeError("str or unicode expected, got a '%s' object"
178-
% (type(text).__name__,))
177+
raise TypeError(f"str or unicode expected, got a '{type(text).__name__}' object")
179178

180179

181180
def _extract_yx(args):
@@ -195,8 +194,7 @@ def _process_args(funcname, args, count, optcount, frontopt=0):
195194
# No front optional args, so make them None.
196195
outargs.extend([None] * frontopt)
197196
if (len(args) < count) or (len(args) > count + optcount):
198-
raise error("%s requires %s to %s arguments" % (
199-
funcname, count, count + optcount + frontopt))
197+
raise error(f"{funcname} requires {count} to {count + optcount + frontopt} arguments")
200198
outargs.extend(args)
201199
return outargs
202200

‎demo/api.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,9 @@ def pyexport(self, signature):
1212
def decorator(func):
1313
name = func.__name__
1414
if name in self._pyexports:
15-
raise cffi.CDefError("duplicate pyexport'ed function %r"
16-
% (name,))
15+
raise cffi.CDefError(f"duplicate pyexport'ed function {name!r}")
1716
callback_var = self.getctype(tp, name)
18-
self.cdef("%s;" % callback_var)
17+
self.cdef(f"{callback_var};")
1918
self._pyexports[name] = _PyExport(tp, func)
2019
return decorator
2120

@@ -24,7 +23,7 @@ def verify(self, source='', **kwargs):
2423
pyexports = sorted(self._pyexports.items())
2524
for name, export in pyexports:
2625
callback_var = self.getctype(export.tp, name)
27-
extras.append("%s;" % callback_var)
26+
extras.append(f"{callback_var};")
2827
extras.append(source)
2928
source = '\n'.join(extras)
3029
lib = FFI.verify(self, source, **kwargs)

‎demo/gmp.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
b = ffi.new("mpz_t")
2323

2424
if len(sys.argv) < 3:
25-
print('call as %s bigint1, bigint2' % sys.argv[0])
25+
print(f'call as {sys.argv[0]} bigint1, bigint2')
2626
sys.exit(2)
2727

2828
lib.mpz_init_set_str(a, sys.argv[1], 10) # Assume decimal integers

‎src/c/test_c.py‎

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ def test_cast_to_signed_char():
174174
p = new_primitive_type("signed char")
175175
x = cast(p, -65 + 17*256)
176176
assert repr(x) == "<cdata 'signed char' -65>"
177-
assert repr(type(x)) == "<%s '_cffi_backend._CDataBase'>" % type_or_class
177+
assert repr(type(x)) == f"<{type_or_class} '_cffi_backend._CDataBase'>"
178178
assert int(x) == -65
179179
x = cast(p, -66 + (1<<199)*256)
180180
assert repr(x) == "<cdata 'signed char' -66>"
@@ -317,9 +317,9 @@ def test_character_type():
317317
assert type(int(cast(p, 'A'))) is int
318318
assert type(long(cast(p, 'A'))) is long
319319
assert str(cast(p, 'A')) == repr(cast(p, 'A'))
320-
assert repr(cast(p, 'A')) == "<cdata 'char' %s'A'>" % mandatory_b_prefix
321-
assert repr(cast(p, 255)) == r"<cdata 'char' %s'\xff'>" % mandatory_b_prefix
322-
assert repr(cast(p, 0)) == r"<cdata 'char' %s'\x00'>" % mandatory_b_prefix
320+
assert repr(cast(p, 'A')) == f"<cdata 'char' {mandatory_b_prefix}'A'>"
321+
assert repr(cast(p, 255)) == rf"<cdata 'char' {mandatory_b_prefix}'\xff'>"
322+
assert repr(cast(p, 0)) == rf"<cdata 'char' {mandatory_b_prefix}'\x00'>"
323323

324324
def test_pointer_type():
325325
p = new_primitive_type("int")
@@ -2231,20 +2231,16 @@ def _test_wchar_variant(typename):
22312231
BInt = new_primitive_type("int")
22322232
pyuni4 = {1: True, 2: False}[len(u+'\U00012345')]
22332233
wchar4 = {2: False, 4: True}[sizeof(BWChar)]
2234-
assert str(cast(BWChar, 0x45)) == "<cdata '%s' %s'E'>" % (
2235-
typename, mandatory_u_prefix)
2236-
assert str(cast(BWChar, 0x1234)) == "<cdata '%s' %s'\u1234'>" % (
2237-
typename, mandatory_u_prefix)
2234+
assert str(cast(BWChar, 0x45)) == f"<cdata '{typename}' {mandatory_u_prefix}'E'>"
2235+
assert str(cast(BWChar, 0x1234)) == f"<cdata '{typename}' {mandatory_u_prefix}'\u1234'>"
22382236
if not _hacked_pypy_uni4():
22392237
if wchar4:
22402238
x = cast(BWChar, 0x12345)
2241-
assert str(x) == "<cdata '%s' %s'\U00012345'>" % (
2242-
typename, mandatory_u_prefix)
2239+
assert str(x) == f"<cdata '{typename}' {mandatory_u_prefix}'\U00012345'>"
22432240
assert int(x) == 0x12345
22442241
else:
22452242
x = cast(BWChar, 0x18345)
2246-
assert str(x) == "<cdata '%s' %s'\u8345'>" % (
2247-
typename, mandatory_u_prefix)
2243+
assert str(x) == f"<cdata '{typename}' {mandatory_u_prefix}'\u8345'>"
22482244
assert int(x) == 0x8345
22492245
#
22502246
BWCharP = new_pointer_type(BWChar)
@@ -2301,26 +2297,25 @@ def _test_wchar_variant(typename):
23012297
a[4]
23022298
#
23032299
w = cast(BWChar, 'a')
2304-
assert repr(w) == "<cdata '%s' %s'a'>" % (typename, mandatory_u_prefix)
2300+
assert repr(w) == f"<cdata '{typename}' {mandatory_u_prefix}'a'>"
23052301
assert str(w) == repr(w)
23062302
assert string(w) == u+'a'
23072303
assert int(w) == ord('a')
23082304
w = cast(BWChar, 0x1234)
2309-
assert repr(w) == "<cdata '%s' %s'\u1234'>" % (typename, mandatory_u_prefix)
2305+
assert repr(w) == f"<cdata '{typename}' {mandatory_u_prefix}'\u1234'>"
23102306
assert str(w) == repr(w)
23112307
assert string(w) == u+'\u1234'
23122308
assert int(w) == 0x1234
23132309
w = cast(BWChar, u+'\u8234')
2314-
assert repr(w) == "<cdata '%s' %s'\u8234'>" % (typename, mandatory_u_prefix)
2310+
assert repr(w) == f"<cdata '{typename}' {mandatory_u_prefix}'\u8234'>"
23152311
assert str(w) == repr(w)
23162312
assert string(w) == u+'\u8234'
23172313
assert int(w) == 0x8234
23182314
w = cast(BInt, u+'\u1234')
23192315
assert repr(w) == "<cdata 'int' 4660>"
23202316
if wchar4 and not _hacked_pypy_uni4():
23212317
w = cast(BWChar, u+'\U00012345')
2322-
assert repr(w) == "<cdata '%s' %s'\U00012345'>" % (
2323-
typename, mandatory_u_prefix)
2318+
assert repr(w) == f"<cdata '{typename}' {mandatory_u_prefix}'\U00012345'>"
23242319
assert str(w) == repr(w)
23252320
assert string(w) == u+'\U00012345'
23262321
assert int(w) == 0x12345
@@ -2349,7 +2344,7 @@ def _test_wchar_variant(typename):
23492344
if is_ios:
23502345
return # cannot allocate executable memory for the callback() below
23512346
def cb(p):
2352-
assert repr(p).startswith("<cdata '%s *' 0x" % typename)
2347+
assert repr(p).startswith(f"<cdata '{typename} *' 0x")
23532348
return len(string(p))
23542349
BFunc = new_function_type((BWCharP,), BInt, False)
23552350
f = callback(BFunc, cb, -42)

‎src/cffi/_cffi_gen_src.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,17 +75,17 @@ def find_ffi_in_python_script(pysrc, filename, ffivar):
7575
_execfile(pysrc, filename, globs)
7676
if ffivar not in globs:
7777
raise NameError(
78-
"Expected to find the FFI object with the name %r, "
79-
"but it was not found." % (ffivar,)
78+
f"Expected to find the FFI object with the name {ffivar!r}, "
79+
"but it was not found."
8080
)
8181
ffi = globs[ffivar]
8282
if not isinstance(ffi, FFI) and callable(ffi):
8383
# Maybe it's a callable that returns a FFI
8484
ffi = ffi()
8585
if not isinstance(ffi, FFI):
8686
raise TypeError(
87-
"Found an object with the name %r but it was not an "
88-
"instance of cffi.api.FFI" % (ffivar,)
87+
f"Found an object with the name {ffivar!r} but it was not an "
88+
"instance of cffi.api.FFI"
8989
)
9090
return ffi
9191
finally:

‎src/cffi/_imp_emulation.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,11 @@ def get_suffixes():
3838

3939
def find_module(name, path=None):
4040
if not isinstance(name, str):
41-
raise TypeError("'name' must be a str, not {}".format(type(name)))
41+
raise TypeError(f"'name' must be a str, not {type(name)}")
4242
elif not isinstance(path, (type(None), list)):
4343
# Backwards-compatibility
4444
raise RuntimeError("'path' must be None or a list, "
45-
"not {}".format(type(path)))
45+
f"not {type(path)}")
4646

4747
if path is None:
4848
if is_builtin(name):

‎src/cffi/api.py‎

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,10 @@ def __init__(self, backend=None):
4444
# bad version! Try to be as explicit as possible.
4545
if hasattr(backend, '__file__'):
4646
# CPython
47-
raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. When we import the top-level '_cffi_backend' extension module, we get version %s, located in %r. The two versions should be equal; check your installation." % (
48-
__version__, __file__,
49-
backend.__version__, backend.__file__))
47+
raise Exception(f"Version mismatch: this is the 'cffi' package version {__version__}, located in {__file__!r}. When we import the top-level '_cffi_backend' extension module, we get version {backend.__version__}, located in {backend.__file__!r}. The two versions should be equal; check your installation.")
5048
else:
5149
# PyPy
52-
raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. This interpreter comes with a built-in '_cffi_backend' module, which is version %s. The two versions should be equal; check your installation." % (
53-
__version__, __file__, backend.__version__))
50+
raise Exception(f"Version mismatch: this is the 'cffi' package version {__version__}, located in {__file__!r}. This interpreter comes with a built-in '_cffi_backend' module, which is version {backend.__version__}. The two versions should be equal; check your installation.")
5451
# (If you insist you can also try to pass the option
5552
# 'backend=backend_ctypes.CTypesBackend()', but don't
5653
# rely on it! It's probably not going to work well.)
@@ -180,8 +177,8 @@ def _typeof(self, cdecl, consider_function_as_funcptr=False):
180177
#
181178
btype, really_a_function_type = result
182179
if really_a_function_type and not consider_function_as_funcptr:
183-
raise CDefError("the type %r is a function type, not a "
184-
"pointer-to-function type" % (cdecl,))
180+
raise CDefError(f"the type {cdecl!r} is a function type, not a "
181+
"pointer-to-function type")
185182
return btype
186183

187184
def typeof(self, cdecl):
@@ -406,7 +403,7 @@ def getctype(self, cdecl, replace_with=''):
406403
replace_with = replace_with.strip()
407404
if (replace_with.startswith('*')
408405
and '&[' in self._backend.getcname(cdecl, '&')):
409-
replace_with = '(%s)' % replace_with
406+
replace_with = f'({replace_with})'
410407
elif replace_with and replace_with[0] not in '[(':
411408
replace_with = ' ' + replace_with
412409
return self._backend.getcname(cdecl, replace_with)
@@ -518,8 +515,7 @@ def include(self, ffi_to_include):
518515
"""
519516
if not isinstance(ffi_to_include, FFI):
520517
raise TypeError("ffi.include() expects an argument that is also of"
521-
" type cffi.FFI, not %r" % (
522-
type(ffi_to_include).__name__,))
518+
f" type cffi.FFI, not {type(ffi_to_include).__name__!r}")
523519
if ffi_to_include is self:
524520
raise ValueError("self.include(self)")
525521
with ffi_to_include._lock:
@@ -589,7 +585,7 @@ def ensure(key, value):
589585
if sys.platform == "win32":
590586
# we need 'libpypy-c.lib'. Current distributions of
591587
# pypy (>= 4.1) contain it as 'libs/python27.lib'.
592-
pythonlib = "python{0[0]}{0[1]}".format(sys.version_info)
588+
pythonlib = f"python{sys.version_info[0]}{sys.version_info[1]}"
593589
if hasattr(sys, 'prefix'):
594590
ensure('library_dirs', os.path.join(sys.prefix, 'libs'))
595591
else:
@@ -671,9 +667,9 @@ def distutils_extension(self, tmpdir='build', verbose=True):
671667
call_c_compiler=False, **kwds)
672668
if verbose:
673669
if updated:
674-
sys.stderr.write("regenerated: %r\n" % (ext.sources[0],))
670+
sys.stderr.write(f"regenerated: {ext.sources[0]!r}\n")
675671
else:
676-
sys.stderr.write("not modified: %r\n" % (ext.sources[0],))
672+
sys.stderr.write(f"not modified: {ext.sources[0]!r}\n")
677673
return ext
678674

679675
def emit_c_code(self, filename):
@@ -816,9 +812,9 @@ def _load_backend_lib(backend, name, flags):
816812
raise OSError("dlopen(None) cannot work on Windows for Python 3 "
817813
"(see http://bugs.python.org/issue23606)")
818814
msg = ("ctypes.util.find_library() did not manage "
819-
"to locate a library called %r" % (name,))
815+
f"to locate a library called {name!r}")
820816
if first_error is not None:
821-
msg = "%s. Additionally, %s" % (first_error, msg)
817+
msg = f"{first_error}. Additionally, {msg}"
822818
raise OSError(msg)
823819
return backend.load_library(path, flags)
824820

@@ -859,8 +855,8 @@ def addressof_var(name):
859855
return addr_variables[name]
860856
#
861857
def accessor_constant(name):
862-
raise NotImplementedError("non-integer constant '%s' cannot be "
863-
"accessed from a dlopen() library" % (name,))
858+
raise NotImplementedError(f"non-integer constant '{name}' cannot be "
859+
"accessed from a dlopen() library")
864860
#
865861
def accessor_int_constant(name):
866862
library.__dict__[name] = ffi._parser._int_constants[name]
@@ -929,7 +925,7 @@ def __addressof__(self, name):
929925
if name in FFILibrary.__dict__:
930926
return addressof_var(name)
931927
raise AttributeError("cffi library has no function or "
932-
"global variable named '%s'" % (name,))
928+
f"global variable named '{name}'")
933929
def __cffi_close__(self):
934930
backendlib.close_lib()
935931
self.__dict__.clear()
@@ -938,7 +934,7 @@ def __cffi_close__(self):
938934
try:
939935
if not isinstance(libname, str): # unicode, on Python 2
940936
libname = libname.encode('utf-8')
941-
FFILibrary.__name__ = 'FFILibrary_%s' % libname
937+
FFILibrary.__name__ = f'FFILibrary_{libname}'
942938
except UnicodeError:
943939
pass
944940
library = FFILibrary()

0 commit comments

Comments
 (0)