From 1715722462a12917273e79f023e5f78597c0c2be Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sun, 19 Jul 2026 22:37:00 +0200 Subject: [PATCH 1/2] Apply ruff/pyupgrade rules UP031 and UP032 These are automatic fixes using: * `--select UP031 --fix --unsafe-fixes` * `--select UP032 --fix` --- demo/_curses.py | 8 +- demo/api.py | 7 +- demo/gmp.py | 2 +- src/c/test_c.py | 31 ++- src/cffi/_cffi_gen_src.py | 8 +- src/cffi/_imp_emulation.py | 4 +- src/cffi/api.py | 34 ++-- src/cffi/backend_ctypes.py | 83 ++++---- src/cffi/cffi_opcode.py | 17 +- src/cffi/commontypes.py | 8 +- src/cffi/cparser.py | 74 ++++--- src/cffi/error.py | 2 +- src/cffi/ffiplatform.py | 4 +- src/cffi/model.py | 51 +++-- src/cffi/pkgconfig.py | 16 +- src/cffi/recompiler.py | 300 +++++++++++++--------------- src/cffi/setuptools_ext.py | 21 +- src/cffi/vengine_cpy.py | 148 +++++++------- src/cffi/vengine_gen.py | 106 +++++----- src/cffi/verifier.py | 8 +- testing/cffi0/backend_tests.py | 6 +- testing/cffi0/test_cdata.py | 4 +- testing/cffi0/test_ffi_backend.py | 14 +- testing/cffi0/test_function.py | 4 +- testing/cffi0/test_ownlib.py | 4 +- testing/cffi0/test_parsing.py | 18 +- testing/cffi0/test_verify.py | 86 ++++---- testing/cffi0/test_version.py | 6 +- testing/cffi0/test_zdistutils.py | 30 +-- testing/cffi1/test_cffi_binary.py | 4 +- testing/cffi1/test_ffi_obj.py | 9 +- testing/cffi1/test_function_args.py | 35 ++-- testing/cffi1/test_new_ffi_1.py | 4 +- testing/cffi1/test_parse_c_type.py | 16 +- testing/cffi1/test_re_python.py | 2 +- testing/cffi1/test_recompiler.py | 16 +- testing/cffi1/test_verify1.py | 84 ++++---- testing/cffi1/test_zdist.py | 6 +- testing/embedding/add1.py | 2 +- testing/embedding/add2.py | 2 +- testing/embedding/add3.py | 2 +- testing/embedding/add_recursive.py | 2 +- testing/embedding/empty.py | 2 +- testing/embedding/initerror.py | 2 +- testing/embedding/perf.py | 2 +- testing/embedding/test_basic.py | 18 +- testing/embedding/tlocal.py | 2 +- testing/embedding/withunicode.py | 2 +- testing/support.py | 7 +- 49 files changed, 615 insertions(+), 708 deletions(-) diff --git a/demo/_curses.py b/demo/_curses.py index 07ede6014..210fa8485 100644 --- a/demo/_curses.py +++ b/demo/_curses.py @@ -97,7 +97,7 @@ def _check_ERR(code, fname): elif fname is None: raise error("curses function returned ERR") else: - raise error("%s() returned ERR" % (fname,)) + raise error(f"{fname}() returned ERR") def _check_NULL(rval): @@ -174,8 +174,7 @@ def _texttype(text): elif isinstance(text, unicode): return str(text) # default encoding else: - raise TypeError("str or unicode expected, got a '%s' object" - % (type(text).__name__,)) + raise TypeError(f"str or unicode expected, got a '{type(text).__name__}' object") def _extract_yx(args): @@ -195,8 +194,7 @@ def _process_args(funcname, args, count, optcount, frontopt=0): # No front optional args, so make them None. outargs.extend([None] * frontopt) if (len(args) < count) or (len(args) > count + optcount): - raise error("%s requires %s to %s arguments" % ( - funcname, count, count + optcount + frontopt)) + raise error(f"{funcname} requires {count} to {count + optcount + frontopt} arguments") outargs.extend(args) return outargs diff --git a/demo/api.py b/demo/api.py index b40af9bfe..86935aecc 100644 --- a/demo/api.py +++ b/demo/api.py @@ -12,10 +12,9 @@ def pyexport(self, signature): def decorator(func): name = func.__name__ if name in self._pyexports: - raise cffi.CDefError("duplicate pyexport'ed function %r" - % (name,)) + raise cffi.CDefError(f"duplicate pyexport'ed function {name!r}") callback_var = self.getctype(tp, name) - self.cdef("%s;" % callback_var) + self.cdef(f"{callback_var};") self._pyexports[name] = _PyExport(tp, func) return decorator @@ -24,7 +23,7 @@ def verify(self, source='', **kwargs): pyexports = sorted(self._pyexports.items()) for name, export in pyexports: callback_var = self.getctype(export.tp, name) - extras.append("%s;" % callback_var) + extras.append(f"{callback_var};") extras.append(source) source = '\n'.join(extras) lib = FFI.verify(self, source, **kwargs) diff --git a/demo/gmp.py b/demo/gmp.py index 90e5e1cfb..2e26f61f4 100644 --- a/demo/gmp.py +++ b/demo/gmp.py @@ -22,7 +22,7 @@ b = ffi.new("mpz_t") if len(sys.argv) < 3: - print('call as %s bigint1, bigint2' % sys.argv[0]) + print(f'call as {sys.argv[0]} bigint1, bigint2') sys.exit(2) lib.mpz_init_set_str(a, sys.argv[1], 10) # Assume decimal integers diff --git a/src/c/test_c.py b/src/c/test_c.py index b2ae3a478..4df5fc66c 100644 --- a/src/c/test_c.py +++ b/src/c/test_c.py @@ -166,7 +166,7 @@ def test_cast_to_signed_char(): p = new_primitive_type("signed char") x = cast(p, -65 + 17*256) assert repr(x) == "" - assert repr(type(x)) == "<%s '_cffi_backend._CDataBase'>" % type_or_class + assert repr(type(x)) == f"<{type_or_class} '_cffi_backend._CDataBase'>" assert int(x) == -65 x = cast(p, -66 + (1<<199)*256) assert repr(x) == "" @@ -309,9 +309,9 @@ def test_character_type(): assert type(int(cast(p, 'A'))) is int assert type(long(cast(p, 'A'))) is long assert str(cast(p, 'A')) == repr(cast(p, 'A')) - assert repr(cast(p, 'A')) == "" % mandatory_b_prefix - assert repr(cast(p, 255)) == r"" % mandatory_b_prefix - assert repr(cast(p, 0)) == r"" % mandatory_b_prefix + assert repr(cast(p, 'A')) == f"" + assert repr(cast(p, 255)) == rf"" + assert repr(cast(p, 0)) == rf"" def test_pointer_type(): p = new_primitive_type("int") @@ -2218,20 +2218,16 @@ def _test_wchar_variant(typename): BInt = new_primitive_type("int") pyuni4 = {1: True, 2: False}[len(u+'\U00012345')] wchar4 = {2: False, 4: True}[sizeof(BWChar)] - assert str(cast(BWChar, 0x45)) == "" % ( - typename, mandatory_u_prefix) - assert str(cast(BWChar, 0x1234)) == "" % ( - typename, mandatory_u_prefix) + assert str(cast(BWChar, 0x45)) == f"" + assert str(cast(BWChar, 0x1234)) == f"" if not _hacked_pypy_uni4(): if wchar4: x = cast(BWChar, 0x12345) - assert str(x) == "" % ( - typename, mandatory_u_prefix) + assert str(x) == f"" assert int(x) == 0x12345 else: x = cast(BWChar, 0x18345) - assert str(x) == "" % ( - typename, mandatory_u_prefix) + assert str(x) == f"" assert int(x) == 0x8345 # BWCharP = new_pointer_type(BWChar) @@ -2288,17 +2284,17 @@ def _test_wchar_variant(typename): a[4] # w = cast(BWChar, 'a') - assert repr(w) == "" % (typename, mandatory_u_prefix) + assert repr(w) == f"" assert str(w) == repr(w) assert string(w) == u+'a' assert int(w) == ord('a') w = cast(BWChar, 0x1234) - assert repr(w) == "" % (typename, mandatory_u_prefix) + assert repr(w) == f"" assert str(w) == repr(w) assert string(w) == u+'\u1234' assert int(w) == 0x1234 w = cast(BWChar, u+'\u8234') - assert repr(w) == "" % (typename, mandatory_u_prefix) + assert repr(w) == f"" assert str(w) == repr(w) assert string(w) == u+'\u8234' assert int(w) == 0x8234 @@ -2306,8 +2302,7 @@ def _test_wchar_variant(typename): assert repr(w) == "" if wchar4 and not _hacked_pypy_uni4(): w = cast(BWChar, u+'\U00012345') - assert repr(w) == "" % ( - typename, mandatory_u_prefix) + assert repr(w) == f"" assert str(w) == repr(w) assert string(w) == u+'\U00012345' assert int(w) == 0x12345 @@ -2336,7 +2331,7 @@ def _test_wchar_variant(typename): if is_ios: return # cannot allocate executable memory for the callback() below def cb(p): - assert repr(p).startswith("= 4.1) contain it as 'libs/python27.lib'. - pythonlib = "python{0[0]}{0[1]}".format(sys.version_info) + pythonlib = f"python{sys.version_info[0]}{sys.version_info[1]}" if hasattr(sys, 'prefix'): ensure('library_dirs', os.path.join(sys.prefix, 'libs')) else: @@ -671,9 +667,9 @@ def distutils_extension(self, tmpdir='build', verbose=True): call_c_compiler=False, **kwds) if verbose: if updated: - sys.stderr.write("regenerated: %r\n" % (ext.sources[0],)) + sys.stderr.write(f"regenerated: {ext.sources[0]!r}\n") else: - sys.stderr.write("not modified: %r\n" % (ext.sources[0],)) + sys.stderr.write(f"not modified: {ext.sources[0]!r}\n") return ext def emit_c_code(self, filename): @@ -816,9 +812,9 @@ def _load_backend_lib(backend, name, flags): raise OSError("dlopen(None) cannot work on Windows for Python 3 " "(see http://bugs.python.org/issue23606)") msg = ("ctypes.util.find_library() did not manage " - "to locate a library called %r" % (name,)) + f"to locate a library called {name!r}") if first_error is not None: - msg = "%s. Additionally, %s" % (first_error, msg) + msg = f"{first_error}. Additionally, {msg}" raise OSError(msg) return backend.load_library(path, flags) @@ -859,8 +855,8 @@ def addressof_var(name): return addr_variables[name] # def accessor_constant(name): - raise NotImplementedError("non-integer constant '%s' cannot be " - "accessed from a dlopen() library" % (name,)) + raise NotImplementedError(f"non-integer constant '{name}' cannot be " + "accessed from a dlopen() library") # def accessor_int_constant(name): library.__dict__[name] = ffi._parser._int_constants[name] @@ -929,7 +925,7 @@ def __addressof__(self, name): if name in FFILibrary.__dict__: return addressof_var(name) raise AttributeError("cffi library has no function or " - "global variable named '%s'" % (name,)) + f"global variable named '{name}'") def __cffi_close__(self): backendlib.close_lib() self.__dict__.clear() @@ -938,7 +934,7 @@ def __cffi_close__(self): try: if not isinstance(libname, str): # unicode, on Python 2 libname = libname.encode('utf-8') - FFILibrary.__name__ = 'FFILibrary_%s' % libname + FFILibrary.__name__ = f'FFILibrary_{libname}' except UnicodeError: pass library = FFILibrary() diff --git a/src/cffi/backend_ctypes.py b/src/cffi/backend_ctypes.py index 12cd16259..ba0c24514 100644 --- a/src/cffi/backend_ctypes.py +++ b/src/cffi/backend_ctypes.py @@ -18,12 +18,11 @@ class CTypesData: __name__ = '' def __init__(self, *args): - raise TypeError("cannot instantiate %r" % (self.__class__,)) + raise TypeError(f"cannot instantiate {self.__class__!r}") @classmethod def _newp(cls, init): - raise TypeError("expected a pointer or array ctype, got '%s'" - % (cls._get_c_name(),)) + raise TypeError(f"expected a pointer or array ctype, got '{cls._get_c_name()}'") @staticmethod def _to_ctypes(value): @@ -34,7 +33,7 @@ def _arg_to_ctypes(cls, *value): try: ctype = cls._ctype except AttributeError: - raise TypeError("cannot create an instance of %r" % (cls,)) + raise TypeError(f"cannot create an instance of {cls!r}") if value: res = cls._to_ctypes(*value) if not isinstance(res, ctype): @@ -60,8 +59,8 @@ def _get_c_name(cls, replace_with=''): @classmethod def _fix_class(cls): - cls.__name__ = 'CData<%s>' % (cls._get_c_name(),) - cls.__qualname__ = 'CData<%s>' % (cls._get_c_name(),) + cls.__name__ = f'CData<{cls._get_c_name()}>' + cls.__qualname__ = f'CData<{cls._get_c_name()}>' cls.__module__ = 'ffi' def _get_own_repr(self): @@ -73,19 +72,17 @@ def _addr_repr(self, address): else: if address < 0: address += 1 << (8*ctypes.sizeof(ctypes.c_void_p)) - return '0x%x' % address + return f'0x{address:x}' def __repr__(self, c_name=None): own = self._get_own_repr() - return '' % (c_name or self._get_c_name(), own) + return f'' def _convert_to_address(self, BClass): if BClass is None: - raise TypeError("cannot convert %r to an address" % ( - self._get_c_name(),)) + raise TypeError(f"cannot convert {self._get_c_name()!r} to an address") else: - raise TypeError("cannot convert %r to %r" % ( - self._get_c_name(), BClass._get_c_name())) + raise TypeError(f"cannot convert {self._get_c_name()!r} to {BClass._get_c_name()!r}") @classmethod def _get_size(cls): @@ -96,7 +93,7 @@ def _get_size_of_instance(self): @classmethod def _cast_from(cls, source): - raise TypeError("cannot cast to %r" % (cls._get_c_name(),)) + raise TypeError(f"cannot cast to {cls._get_c_name()!r}") def _cast_to_integer(self): return self._convert_to_address(None) @@ -106,8 +103,7 @@ def _alignment(cls): return ctypes.alignment(cls._ctype) def __iter__(self): - raise TypeError("cdata %r does not support iteration" % ( - self._get_c_name()),) + raise TypeError(f"cdata {self._get_c_name()!r} does not support iteration",) def _make_cmp(name): cmpfunc = getattr(operator, name) @@ -140,7 +136,7 @@ def __hash__(self): return hash(self._convert_to_address(None)) def _to_string(self, maxlen): - raise TypeError("string(): %r" % (self,)) + raise TypeError(f"string(): {self!r}") class CTypesGenericPrimitive(CTypesData): @@ -186,8 +182,7 @@ def _cast_from(cls, source): elif isinstance(source, (int, long)): address = source else: - raise TypeError("bad type for cast to %r: %r" % - (cls, type(source).__name__)) + raise TypeError(f"bad type for cast to {cls!r}: {type(source).__name__!r}") return cls._new_pointer_at(address) @classmethod @@ -213,7 +208,7 @@ def __nonzero__(self): @classmethod def _to_ctypes(cls, value): if not isinstance(value, CTypesData): - raise TypeError("unexpected %s object" % type(value).__name__) + raise TypeError(f"unexpected {type(value).__name__} object") address = value._convert_to_address(cls) return ctypes.cast(address, cls._ctype) @@ -241,7 +236,7 @@ class CTypesBaseStructOrUnion(CTypesData): @classmethod def _create_ctype_obj(cls, init): # may be overridden - raise TypeError("cannot instantiate opaque type %s" % (cls,)) + raise TypeError(f"cannot instantiate opaque type {cls}") def _get_own_repr(self): return self._addr_repr(ctypes.addressof(self._blob)) @@ -334,8 +329,7 @@ def _from_ctypes(novalue): @staticmethod def _to_ctypes(novalue): if novalue is not None: - raise TypeError("None expected, got %s object" % - (type(novalue).__name__,)) + raise TypeError(f"None expected, got {type(novalue).__name__} object") CTypesVoid._fix_class() return CTypesVoid @@ -366,15 +360,14 @@ def _cast_source_to_int(source): elif source is None: source = 0 else: - raise TypeError("bad type for cast to %r: %r" % - (CTypesPrimitive, type(source).__name__)) + raise TypeError(f"bad type for cast to {CTypesPrimitive!r}: {type(source).__name__!r}") return source # kind1 = kind class CTypesPrimitive(CTypesGenericPrimitive): __slots__ = ['_value'] _ctype = ctype - _reftypename = '%s &' % name + _reftypename = f'{name} &' kind = kind1 def __init__(self, value): @@ -441,14 +434,12 @@ def _to_ctypes(x): if isinstance(x, CTypesData): x = int(x) else: - raise TypeError("integer expected, got %s" % - type(x).__name__) + raise TypeError(f"integer expected, got {type(x).__name__}") if ctype(x).value != x: if not is_signed and x < 0: - raise OverflowError("%s: negative integer" % name) + raise OverflowError(f"{name}: negative integer") else: - raise OverflowError("%s: integer out of bounds" - % name) + raise OverflowError(f"{name}: integer out of bounds") return x if kind == 'char': @@ -458,8 +449,7 @@ def _to_ctypes(x): return x if isinstance(x, CTypesPrimitive): # > return x._value - raise TypeError("character expected, got %s" % - type(x).__name__) + raise TypeError(f"character expected, got {type(x).__name__}") def __nonzero__(self): return ord(self._value) != 0 else: @@ -471,8 +461,7 @@ def __nonzero__(self): @staticmethod def _to_ctypes(x): if not isinstance(x, (int, long, float, CTypesData)): - raise TypeError("float expected, got %s" % - type(x).__name__) + raise TypeError(f"float expected, got {type(x).__name__}") return ctype(x).value @staticmethod @@ -638,7 +627,7 @@ def _initialize(blob, init): if isinstance(init, CTypesGenericArray): if (len(init) != len(blob) or not isinstance(init, CTypesArray)): - raise TypeError("length/type mismatch: %s" % (init,)) + raise TypeError(f"length/type mismatch: {init}") init = tuple(init) if len(init) > len(blob): raise IndexError("too many initializers") @@ -704,8 +693,7 @@ def __add__(self, other): @classmethod def _cast_from(cls, source): - raise NotImplementedError("casting to %r" % ( - cls._get_c_name(),)) + raise NotImplementedError(f"casting to {cls._get_c_name()!r}") # CTypesArray._fix_class() return CTypesArray @@ -714,13 +702,13 @@ def _new_struct_or_union(self, kind, name, base_ctypes_class): # class struct_or_union(base_ctypes_class): pass - struct_or_union.__name__ = '%s_%s' % (kind, name) + struct_or_union.__name__ = f'{kind}_{name}' kind1 = kind # class CTypesStructOrUnion(CTypesBaseStructOrUnion): __slots__ = ['_blob'] _ctype = struct_or_union - _reftypename = '%s &' % (name,) + _reftypename = f'{name} &' _kind = kind = kind1 # CTypesStructOrUnion._fix_class() @@ -779,8 +767,7 @@ def initialize(blob, init): raise TypeError("union initializer: got a str") init = tuple(init) if len(init) > len(fnames): - raise ValueError("too many values for %s initializer" % - CTypesStructOrUnion._get_c_name()) + raise ValueError(f"too many values for {CTypesStructOrUnion._get_c_name()} initializer") init = dict(zip(fnames, init)) addr = ctypes.addressof(blob) for fname, value in init.items(): @@ -798,8 +785,8 @@ def initialize(blob, init): if fname == '': raise NotImplementedError("nested anonymous structs/unions") if hasattr(CTypesStructOrUnion, fname): - raise ValueError("the field name %r conflicts in " - "the ctypes backend" % fname) + raise ValueError(f"the field name {fname!r} conflicts in " + "the ctypes backend") if bitsize < 0: def getter(self, fname=fname, BField=BField, offset=CTypesStructOrUnion._offsetof(fname), @@ -836,8 +823,8 @@ def setter(self, value, fname=fname, BField=BField): CTypesPtr = self.ffi._get_cached_btype(model.PointerType(tp)) for fname in fnames: if hasattr(CTypesPtr, fname): - raise ValueError("the field name %r conflicts in " - "the ctypes backend" % fname) + raise ValueError(f"the field name {fname!r} conflicts in " + "the ctypes backend") def getter(self, fname=fname): return getattr(self[0], fname) def setter(self, value, fname=fname): @@ -855,7 +842,7 @@ class CTypesFunctionPtr(CTypesGenericPtr): _ctype = ctypes.CFUNCTYPE(getattr(BResult, '_ctype', None), *[BArg._ctype for BArg in BArgs], use_errno=True) - _reftypename = BResult._get_c_name('(* &)(%s)' % (nameargs,)) + _reftypename = BResult._get_c_name(f'(* &)({nameargs})') def __init__(self, init, error=None): # create a callback to the Python callable init() @@ -915,7 +902,7 @@ def __repr__(self): def _get_own_repr(self): if getattr(self, '_own_callback', None) is not None: - return 'calling %r' % (self._own_callback,) + return f'calling {self._own_callback!r}' return super()._get_own_repr() def __call__(self, *args): @@ -952,7 +939,7 @@ def new_enum_type(self, name, enumerators, enumvalues, CTypesInt): # class CTypesEnum(CTypesInt): __slots__ = [] - _reftypename = '%s &' % name + _reftypename = f'{name} &' def _get_own_repr(self): value = self._value diff --git a/src/cffi/cffi_opcode.py b/src/cffi/cffi_opcode.py index c964ba13e..7cb8ee822 100644 --- a/src/cffi/cffi_opcode.py +++ b/src/cffi/cffi_opcode.py @@ -8,31 +8,26 @@ def __init__(self, op, arg): def as_c_expr(self): if self.op is None: assert isinstance(self.arg, str) - return '(_cffi_opcode_t)(%s)' % (self.arg,) + return f'(_cffi_opcode_t)({self.arg})' classname = CLASS_NAME[self.op] - return '_CFFI_OP(_CFFI_OP_%s, %s)' % (classname, self.arg) + return f'_CFFI_OP(_CFFI_OP_{classname}, {self.arg})' def as_python_bytes(self): if self.op is None and self.arg.isdigit(): value = int(self.arg) # non-negative: '-' not in self.arg if value >= 2**31: - raise OverflowError("cannot emit %r: limited to 2**31-1" - % (self.arg,)) + raise OverflowError(f"cannot emit {self.arg!r}: limited to 2**31-1") return format_four_bytes(value) if isinstance(self.arg, str): - raise VerificationError("cannot emit to Python: %r" % (self.arg,)) + raise VerificationError(f"cannot emit to Python: {self.arg!r}") return format_four_bytes((self.arg << 8) | self.op) def __str__(self): classname = CLASS_NAME.get(self.op, self.op) - return '(%s %s)' % (classname, self.arg) + return f'({classname} {self.arg})' def format_four_bytes(num): - return '\\x%02X\\x%02X\\x%02X\\x%02X' % ( - (num >> 24) & 0xFF, - (num >> 16) & 0xFF, - (num >> 8) & 0xFF, - (num ) & 0xFF) + return f'\\x{(num >> 24) & 0xFF:02X}\\x{(num >> 16) & 0xFF:02X}\\x{(num >> 8) & 0xFF:02X}\\x{(num ) & 0xFF:02X}' OP_PRIMITIVE = 1 OP_POINTER = 3 diff --git a/src/cffi/commontypes.py b/src/cffi/commontypes.py index d4dae3517..8d77068de 100644 --- a/src/cffi/commontypes.py +++ b/src/cffi/commontypes.py @@ -34,15 +34,15 @@ def resolve_common_type(parser, commontype): elif cdecl in model.PrimitiveType.ALL_PRIMITIVE_TYPES: result, quals = model.PrimitiveType(cdecl), 0 elif cdecl == 'set-unicode-needed': - raise FFIError("The Windows type %r is only available after " - "you call ffi.set_unicode()" % (commontype,)) + raise FFIError(f"The Windows type {commontype!r} is only available after " + "you call ffi.set_unicode()") else: if commontype == cdecl: raise FFIError( - "Unsupported type: %r. Please look at " + f"Unsupported type: {commontype!r}. Please look at " "http://cffi.readthedocs.io/en/latest/cdef.html#ffi-cdef-limitations " "and file an issue if you think this type should really " - "be supported." % (commontype,)) + "be supported.") result, quals = parser.parse_type_and_quals(cdecl) # recursive assert isinstance(result, model.BaseTypeByIdentity) diff --git a/src/cffi/cparser.py b/src/cffi/cparser.py index 1896b7ef5..157a3f635 100644 --- a/src/cffi/cparser.py +++ b/src/cffi/cparser.py @@ -160,9 +160,9 @@ def _warn_for_string_literal(csource): def _warn_for_non_extern_non_static_global_variable(decl): if not decl.storage: import warnings - warnings.warn("Global variable '%s' in cdef(): for consistency " + warnings.warn(f"Global variable '{decl.name}' in cdef(): for consistency " "with C it should have a storage class specifier " - "(usually 'extern')" % (decl.name,)) + "(usually 'extern')") def _remove_line_directives(csource): # _r_line_directive matches whole lines, without the final \n, if they @@ -322,12 +322,12 @@ def _parse(self, csource): csourcelines = [] csourcelines.append('# 1 ""') for typename in typenames: - csourcelines.append('typedef int %s;' % typename) + csourcelines.append(f'typedef int {typename};') csourcelines.append('typedef int __dotdotdotint__, __dotdotdotfloat__,' ' __dotdotdot__;') # this forces pycparser to consider the following in the file # called from line 1 - csourcelines.append('# 1 "%s"' % (CDEF_SOURCE_STRING,)) + csourcelines.append(f'# 1 "{CDEF_SOURCE_STRING}"') csourcelines.append(csource) csourcelines.append('') # see test_missing_newline_bug fullcsource = '\n'.join(csourcelines) @@ -349,7 +349,7 @@ def _convert_pycparser_error(self, e, csource): # the user gives explicit ``# NUM "FILE"`` directives. line = None msg = str(e) - match = re.match(r"%s:(\d+):" % (CDEF_SOURCE_STRING,), msg) + match = re.match(rf"{CDEF_SOURCE_STRING}:(\d+):", msg) if match: linenum = int(match.group(1), 10) csourcelines = csource.splitlines() @@ -362,9 +362,9 @@ def convert_pycparser_error(self, e, csource): msg = str(e) if line: - msg = 'cannot parse "%s"\n%s' % (line.strip(), msg) + msg = f'cannot parse "{line.strip()}"\n{msg}' else: - msg = 'parse error\n%s' % (msg,) + msg = f'parse error\n{msg}' raise CDefError(msg) def parse(self, csource, override=False, packed=False, pack=None, @@ -378,8 +378,7 @@ def parse(self, csource, override=False, packed=False, pack=None, pack = 1 elif pack: if pack & (pack - 1): - raise ValueError("'pack' must be a power of two, not %r" % - (pack,)) + raise ValueError(f"'pack' must be a power of two, not {pack!r}") else: pack = 0 prev_options = self._options @@ -428,7 +427,7 @@ def _internal_parse(self, csource): else: realtype, quals = self._get_type_and_quals( decl.type, name=decl.name, partial_length_ok=True, - typedef_example="*(%s *)0" % (decl.name,)) + typedef_example=f"*({decl.name} *)0") self._declare('typedef ' + decl.name, realtype, quals=quals) elif decl.__class__.__name__ == 'Pragma': # skip pragma, only in pycparser 2.15 @@ -441,9 +440,8 @@ def _internal_parse(self, csource): "'#pragma pack' needs to be replaced with the " "'packed' keyword argument to cdef().") else: - raise CDefError("unexpected <%s>: this construct is valid " - "C but not valid in cdef()" % - decl.__class__.__name__, decl) + raise CDefError(f"unexpected <{decl.__class__.__name__}>: this construct is valid " + "C but not valid in cdef()", decl) except CDefError as e: if len(e.args) == 1: e.args = e.args + (current_decl,) @@ -451,7 +449,7 @@ def _internal_parse(self, csource): except FFIError as e: msg = self._convert_pycparser_error(e, csource) if msg: - e.args = (e.args[0] + "\n *** Err: %s" % msg,) + e.args = (e.args[0] + f"\n *** Err: {msg}",) raise def _add_constants(self, key, val): @@ -459,7 +457,7 @@ def _add_constants(self, key, val): if self._int_constants[key] == val: return # ignore identical double declarations raise FFIError( - "multiple declarations of constant: %s" % (key,)) + f"multiple declarations of constant: {key}") self._int_constants[key] = val def _add_integer_constant(self, name, int_str): @@ -487,12 +485,11 @@ def _process_macros(self, macros): else: raise CDefError( 'only supports one of the following syntax:\n' - ' #define %s ... (literally dot-dot-dot)\n' - ' #define %s NUMBER (with NUMBER an integer' + f' #define {key} ... (literally dot-dot-dot)\n' + f' #define {key} NUMBER (with NUMBER an integer' ' constant, decimal/hex/octal)\n' 'got:\n' - ' #define %s %s' - % (key, key, key, value)) + f' #define {key} {value}') def _declare_function(self, tp, quals, decl): tp = self._get_type_pointer(tp, quals) @@ -561,11 +558,11 @@ def parse_type(self, cdecl): return self.parse_type_and_quals(cdecl)[0] def parse_type_and_quals(self, cdecl): - ast, macros = self._parse('void __dummy(\n%s\n);' % cdecl)[:2] + ast, macros = self._parse(f'void __dummy(\n{cdecl}\n);')[:2] assert not macros exprnode = ast.ext[-1].type.args.params[0] if isinstance(exprnode, pycparser.c_ast.ID): - raise CDefError("unknown identifier '%s'" % (exprnode.name,)) + raise CDefError(f"unknown identifier '{exprnode.name}'") return self._get_type_and_quals(exprnode.type) def _declare(self, name, obj, included=False, quals=0): @@ -575,8 +572,8 @@ def _declare(self, name, obj, included=False, quals=0): return if not self._options.get('override'): raise FFIError( - "multiple declarations of %s (for interactive usage, " - "try cdef(xx, override=True))" % (name,)) + f"multiple declarations of {name} (for interactive usage, " + "try cdef(xx, override=True))") assert '__dotdotdot__' not in name.split() self._declarations[name] = (obj, quals) if included: @@ -627,7 +624,7 @@ def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False, # many more places within recompiler.py if typedef_example is not None: if length == '...': - length = '_cffi_array_len(%s)' % (typedef_example,) + length = f'_cffi_array_len({typedef_example})' typedef_example = "*" + typedef_example # tp, quals = self._get_type_and_quals(typenode.type, @@ -781,14 +778,14 @@ def _get_struct_union_enum_type(self, kind, type, name=None, nested=False): # 'force_name' is used to guess a more readable name for # anonymous structs, for the common case "typedef struct { } foo". if force_name is not None: - explicit_name = '$%s' % force_name + explicit_name = f'${force_name}' else: self._anonymous_counter += 1 explicit_name = '$%d' % self._anonymous_counter tp = None else: explicit_name = name - key = '%s %s' % (kind, name) + key = f'{kind} {name}' tp, _ = self._declarations.get(key, (None, None)) # if tp is None: @@ -801,17 +798,17 @@ def _get_struct_union_enum_type(self, kind, type, name=None, nested=False): raise CDefError("Enums cannot be declared with ...") tp = self._build_enum_type(explicit_name, type.values) else: - raise AssertionError("kind = %r" % (kind,)) + raise AssertionError(f"kind = {kind!r}") if name is not None: self._declare(key, tp) elif kind == 'enum' and type.values is not None: raise NotImplementedError( - "enum %s: the '{}' declaration should appear on the first " - "time the enum is mentioned, not later" % explicit_name) + f"enum {explicit_name}: the '{{}}' declaration should appear on the first " + "time the enum is mentioned, not later") if not tp.forcename: tp.force_the_name(force_name) if tp.forcename and '$' in tp.name: - self._declare('anonymous %s' % tp.forcename, tp) + self._declare(f'anonymous {tp.forcename}', tp) # self._structnode2type[type] = tp # @@ -826,7 +823,7 @@ def _get_struct_union_enum_type(self, kind, type, name=None, nested=False): return tp # if tp.fldnames is not None: - raise CDefError("duplicate declaration of struct %s" % name) + raise CDefError(f"duplicate declaration of struct {name}") fldnames = [] fldtypes = [] fldbitsize = [] @@ -860,8 +857,7 @@ def _get_struct_union_enum_type(self, kind, type, name=None, nested=False): tp.fldquals = tuple(fldquals) if fldbitsize != [-1] * len(fldbitsize): if isinstance(tp, model.StructType) and tp.partial: - raise NotImplementedError("%s: using both bitfields and '...;'" - % (tp,)) + raise NotImplementedError(f"{tp}: using both bitfields and '...;'") tp.packed = self._options.get('packed') if tp.completed: # must be re-completed: it is not opaque any more tp.completed = 0 @@ -870,9 +866,9 @@ def _get_struct_union_enum_type(self, kind, type, name=None, nested=False): def _make_partial(self, tp, nested): if not isinstance(tp, model.StructOrUnion): - raise CDefError("%s cannot be partial" % (tp,)) + raise CDefError(f"{tp} cannot be partial") if not tp.has_c_name() and not nested: - raise NotImplementedError("%s is partial but has no C name" %(tp,)) + raise NotImplementedError(f"{tp} is partial but has no C name") tp.partial = True def _parse_constant(self, exprnode, partial_length_ok=False): @@ -893,12 +889,12 @@ def _parse_constant(self, exprnode, partial_length_ok=False): return int(s, 16) elif s.lower()[0:2] == '0b': return int(s, 2) - raise CDefError("invalid constant %r" % (s,)) + raise CDefError(f"invalid constant {s!r}") elif s[0] == "'" and s[-1] == "'" and ( len(s) == 3 or (len(s) == 4 and s[1] == "\\")): return ord(s[-2]) else: - raise CDefError("invalid constant %r" % (s,)) + raise CDefError(f"invalid constant {s!r}") # if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and exprnode.op == '+'): @@ -995,13 +991,13 @@ def _get_unknown_type(self, decl): if typenames == ['__dotdotdotint__']: if self._uses_new_feature is None: - self._uses_new_feature = "'typedef int... %s'" % decl.name + self._uses_new_feature = f"'typedef int... {decl.name}'" return model.UnknownIntegerType(decl.name) if typenames == ['__dotdotdotfloat__']: # note: not for 'long double' so far if self._uses_new_feature is None: - self._uses_new_feature = "'typedef float... %s'" % decl.name + self._uses_new_feature = f"'typedef float... {decl.name}'" return model.UnknownFloatType(decl.name) raise FFIError(':%d: unsupported usage of "..." in typedef' diff --git a/src/cffi/error.py b/src/cffi/error.py index 0a27247c3..1ab037696 100644 --- a/src/cffi/error.py +++ b/src/cffi/error.py @@ -12,7 +12,7 @@ def __str__(self): prefix = '%s:%d: ' % (filename, linenum) except (AttributeError, TypeError, IndexError): prefix = '' - return '%s%s' % (prefix, self.args[0]) + return f'{prefix}{self.args[0]}' class VerificationError(Exception): """ An error raised when verification fails diff --git a/src/cffi/ffiplatform.py b/src/cffi/ffiplatform.py index adca28f1a..a3f40a8fe 100644 --- a/src/cffi/ffiplatform.py +++ b/src/cffi/ffiplatform.py @@ -51,7 +51,7 @@ def _build(tmpdir, ext, compiler_verbose=0, debug=None): finally: set_threshold(old_level) except (CompileError, LinkError) as e: - raise VerificationError('%s: %s' % (e.__class__.__name__, e)) + raise VerificationError(f'{e.__class__.__name__}: {e}') # return soname @@ -105,7 +105,7 @@ def _flatten(x, f): f.write('%di' % (x,)) else: raise TypeError( - "the keywords to verify() contains unsupported object %r" % (x,)) + f"the keywords to verify() contains unsupported object {x!r}") def flatten(x): f = cStringIO.StringIO() diff --git a/src/cffi/model.py b/src/cffi/model.py index 8bade1d6d..d12424c7b 100644 --- a/src/cffi/model.py +++ b/src/cffi/model.py @@ -33,15 +33,14 @@ def get_c_name(self, replace_with='', context='a C file', quals=0): replace_with = replace_with.strip() if replace_with: if replace_with.startswith('*') and '&[' in result: - replace_with = '(%s)' % replace_with + replace_with = f'({replace_with})' elif replace_with[0] not in '[(': replace_with = ' ' + replace_with replace_with = qualify(quals, replace_with) result = result.replace('&', replace_with) if '$' in result: raise VerificationError( - "cannot generate '%s' in %s: unknown type name" - % (self._get_c_name(), context)) + f"cannot generate '{self._get_c_name()}' in {context}: unknown type name") return result def _get_c_name(self): @@ -63,7 +62,7 @@ def get_cached_btype(self, ffi, finishlist, can_delay=False): return BType def __repr__(self): - return '<%s>' % (self._get_c_name(),) + return f'<{self._get_c_name()}>' def _get_items(self): return [(name, getattr(self, name)) for name in self._attrs_] @@ -186,8 +185,8 @@ def is_integer_type(self): return True def build_backend_type(self, ffi, finishlist): - raise NotImplementedError("integer type '%s' can only be used after " - "compilation" % self.name) + raise NotImplementedError(f"integer type '{self.name}' can only be used after " + "compilation") class UnknownFloatType(BasePrimitiveType): _attrs_ = ('name', ) @@ -197,8 +196,8 @@ def __init__(self, name): self.c_name_with_marker = name + '&' def build_backend_type(self, ffi, finishlist): - raise NotImplementedError("float type '%s' can only be used after " - "compilation" % self.name) + raise NotImplementedError(f"float type '{self.name}' can only be used after " + "compilation") class BaseFunctionType(BaseType): @@ -229,8 +228,8 @@ class RawFunctionType(BaseFunctionType): is_raw_function = True def build_backend_type(self, ffi, finishlist): - raise CDefError("cannot render the type %r: it is a function " - "type, not a pointer-to-function type" % (self,)) + raise CDefError(f"cannot render the type {self!r}: it is a function " + "type, not a pointer-to-function type") def as_function_pointer(self): return FunctionPtrType(self.args, self.result, self.ellipsis, self.abi) @@ -266,7 +265,7 @@ def __init__(self, totype, quals=0): self.quals = quals extra = " *&" if totype.is_array_type: - extra = "(%s)" % (extra.lstrip(),) + extra = f"({extra.lstrip()})" extra = qualify(quals, extra) self.c_name_with_marker = totype.c_name_with_marker.replace('&', extra) @@ -304,7 +303,7 @@ def __init__(self, item, length): elif length == '...': brackets = '&[/*...*/]' else: - brackets = '&[%s]' % length + brackets = f'&[{length}]' self.c_name_with_marker = ( self.item.c_name_with_marker.replace('&', brackets)) @@ -316,8 +315,7 @@ def resolve_length(self, newlength): def build_backend_type(self, ffi, finishlist): if self.length_is_unknown(): - raise CDefError("cannot render the type %r: unknown length" % - (self,)) + raise CDefError(f"cannot render the type {self!r}: unknown length") self.item.get_cached_btype(ffi, finishlist) # force the item BType BPtrItem = PointerType(self.item).get_cached_btype(ffi, finishlist) return global_cache(self, ffi, 'new_array_type', BPtrItem, self.length) @@ -330,7 +328,7 @@ class StructOrUnionOrEnum(BaseTypeByIdentity): forcename = None def build_c_name_with_marker(self): - name = self.forcename or '%s %s' % (self.kind, self.name) + name = self.forcename or f'{self.kind} {self.name}' self.c_name_with_marker = name + '&' def force_the_name(self, forcename): @@ -404,7 +402,7 @@ def finish_backend_type(self, ffi, finishlist): if self.completed: if self.completed != 2: raise NotImplementedError("recursive structure declaration " - "for '%s'" % (self.name,)) + f"for '{self.name}'") return BType = ffi._cached_btypes[self] # @@ -439,7 +437,7 @@ def finish_backend_type(self, ffi, finishlist): nlen, nrest = divmod(fsize, ffi.sizeof(BItemType)) if nrest != 0: self._verification_error( - "field '%s.%s' has a bogus size?" % ( + "field '{}.{}' has a bogus size?".format( self.name, self.fldnames[i] or '{}')) ftype = ftype.resolve_length(nlen) self.fldtypes = (self.fldtypes[:i] + (ftype,) + @@ -474,7 +472,7 @@ def build_backend_type(self, ffi, finishlist): self.check_not_partial() finishlist.append(self) # - return global_cache(self, ffi, 'new_%s_type' % self.kind, + return global_cache(self, ffi, f'new_{self.kind}_type', self.get_official_name(), key=self) @@ -532,9 +530,8 @@ def build_baseinttype(self, ffi, finishlist): __warningregistry__.clear() except NameError: pass - warnings.warn("%r has no values explicitly defined; " - "guessing that it is equivalent to 'unsigned int'" - % self._get_c_name()) + warnings.warn(f"{self._get_c_name()!r} has no values explicitly defined; " + "guessing that it is equivalent to 'unsigned int'") smallest_value = largest_value = 0 if smallest_value < 0: # needs a signed type sign = 1 @@ -554,12 +551,12 @@ def build_baseinttype(self, ffi, finishlist): if (smallest_value >= ((-1) << (8*size2-1)) and largest_value < (1 << (8*size2-sign))): return btype2 - raise CDefError("%s values don't all fit into either 'long' " - "or 'unsigned long'" % self._get_c_name()) + raise CDefError(f"{self._get_c_name()} values don't all fit into either 'long' " + "or 'unsigned long'") def unknown_type(name, structname=None): if structname is None: - structname = '$%s' % name + structname = f'${name}' tp = StructType(structname, None, None, None) tp.force_the_name(name) tp.origin = "unknown_type" @@ -567,7 +564,7 @@ def unknown_type(name, structname=None): def unknown_ptr_type(name, structname=None): if structname is None: - structname = '$$%s' % name + structname = f'$${name}' tp = StructType(structname, None, None, None) return NamedPointerType(tp, name) @@ -596,7 +593,7 @@ def global_cache(srctype, ffi, funcname, *args, **kwds): try: res = getattr(ffi._backend, funcname)(*args) except NotImplementedError as e: - raise NotImplementedError("%s: %r: %s" % (funcname, srctype, e)) + raise NotImplementedError(f"{funcname}: {srctype!r}: {e}") # note that setdefault() on WeakValueDictionary is not atomic # and contains a rare bug (http://bugs.python.org/issue19542); # we have to use a lock and do it ourselves @@ -614,4 +611,4 @@ def pointer_cache(ffi, BType): def attach_exception_info(e, name): if e.args and type(e.args[0]) is str: - e.args = ('%s: %s' % (name, e.args[0]),) + e.args[1:] + e.args = (f'{name}: {e.args[0]}',) + e.args[1:] diff --git a/src/cffi/pkgconfig.py b/src/cffi/pkgconfig.py index e1034ad68..4cd5a4082 100644 --- a/src/cffi/pkgconfig.py +++ b/src/cffi/pkgconfig.py @@ -16,9 +16,9 @@ def merge_flags(cfg1, cfg2): cfg1[key] = value else: if not isinstance(cfg1[key], list): - raise TypeError("cfg1[%r] should be a list of strings" % (key,)) + raise TypeError(f"cfg1[{key!r}] should be a list of strings") if not isinstance(value, list): - raise TypeError("cfg2[%r] should be a list of strings" % (key,)) + raise TypeError(f"cfg2[{key!r}] should be a list of strings") cfg1[key].extend(value) return cfg1 @@ -32,7 +32,7 @@ def call(libname, flag, encoding=sys.getfilesystemencoding()): try: pc = subprocess.Popen(a, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError as e: - raise PkgConfigError("cannot run pkg-config: %s" % (str(e).strip(),)) + raise PkgConfigError(f"cannot run pkg-config: {str(e).strip()}") bout, berr = pc.communicate() if pc.returncode != 0: @@ -46,14 +46,12 @@ def call(libname, flag, encoding=sys.getfilesystemencoding()): try: bout = bout.decode(encoding) except UnicodeDecodeError: - raise PkgConfigError("pkg-config %s %s returned bytes that cannot " - "be decoded with encoding %r:\n%r" % - (flag, libname, encoding, bout)) + raise PkgConfigError(f"pkg-config {flag} {libname} returned bytes that cannot " + f"be decoded with encoding {encoding!r}:\n{bout!r}") if os.altsep != '\\' and '\\' in bout: - raise PkgConfigError("pkg-config %s %s returned an unsupported " - "backslash-escaped output:\n%r" % - (flag, libname, bout)) + raise PkgConfigError(f"pkg-config {flag} {libname} returned an unsupported " + f"backslash-escaped output:\n{bout!r}") return bout diff --git a/src/cffi/recompiler.py b/src/cffi/recompiler.py index 5e71aed9a..3613e45c6 100644 --- a/src/cffi/recompiler.py +++ b/src/cffi/recompiler.py @@ -22,8 +22,7 @@ def __init__(self, name, address, type_op, size=0, check_value=0): self.check_value = check_value def as_c_expr(self): - return ' { "%s", (void *)%s, %s, (void *)%s },' % ( - self.name, self.address, self.type_op.as_c_expr(), self.size) + return f' {{ "{self.name}", (void *){self.address}, {self.type_op.as_c_expr()}, (void *){self.size} }},' def as_python_expr(self): return "b'%s%s',%d" % (self.type_op.as_python_bytes(), self.name, @@ -39,9 +38,9 @@ def __init__(self, name, field_offset, field_size, fbitsize, field_type_op): def as_c_expr(self): spaces = " " * len(self.name) - return (' { "%s", %s,\n' % (self.name, self.field_offset) + - ' %s %s,\n' % (spaces, self.field_size) + - ' %s %s },' % (spaces, self.field_type_op.as_c_expr())) + return (f' {{ "{self.name}", {self.field_offset},\n' + + f' {spaces} {self.field_size},\n' + + f' {spaces} {self.field_type_op.as_c_expr()} }},') def as_python_expr(self): raise NotImplementedError @@ -53,9 +52,7 @@ def as_field_python_expr(self): size_expr = format_four_bytes(self.fbitsize) else: raise NotImplementedError - return "b'%s%s%s'" % (self.field_type_op.as_python_bytes(), - size_expr, - self.name) + return f"b'{self.field_type_op.as_python_bytes()}{size_expr}{self.name}'" class StructUnionExpr: def __init__(self, name, type_index, flags, size, alignment, comment, @@ -71,16 +68,16 @@ def __init__(self, name, type_index, flags, size, alignment, comment, def as_c_expr(self): return (' { "%s", %d, %s,' % (self.name, self.type_index, self.flags) - + '\n %s, %s, ' % (self.size, self.alignment) + + f'\n {self.size}, {self.alignment}, ' + '%d, %d ' % (self.first_field_index, len(self.c_fields)) - + ('/* %s */ ' % self.comment if self.comment else '') + + (f'/* {self.comment} */ ' if self.comment else '') + '},') def as_python_expr(self): flags = eval(self.flags, G_FLAGS) fields_expr = [c_field.as_field_python_expr() for c_field in self.c_fields] - return "(b'%s%s%s',%s)" % ( + return "(b'{}{}{}',{})".format( format_four_bytes(self.type_index), format_four_bytes(flags), self.name, @@ -103,9 +100,9 @@ def as_c_expr(self): if j < 0: break j += 1 - lines.append(' "%s"' % (self.allenums[pending:j],)) + lines.append(f' "{self.allenums[pending:j]}"') pending = j - lines.append(' "%s" },' % (self.allenums[pending:],)) + lines.append(f' "{self.allenums[pending:]}" }},') return '\n'.join(lines) def as_python_expr(self): @@ -115,9 +112,7 @@ def as_python_expr(self): (4, 0): PRIM_UINT32, (4, 1): PRIM_INT32, (8, 0): PRIM_UINT64, (8, 1): PRIM_INT64, }[self.size, self.signed] - return "b'%s%s%s\\x00%s'" % (format_four_bytes(self.type_index), - format_four_bytes(prim_index), - self.name, self.allenums) + return f"b'{format_four_bytes(self.type_index)}{format_four_bytes(prim_index)}{self.name}\\x00{self.allenums}'" class TypenameExpr: def __init__(self, name, type_index): @@ -128,7 +123,7 @@ def as_c_expr(self): return ' { "%s", %d },' % (self.name, self.type_index) def as_python_expr(self): - return "b'%s%s'" % (format_four_bytes(self.type_index), self.name) + return f"b'{format_four_bytes(self.type_index)}{self.name}'" # ____________________________________________________________ @@ -239,11 +234,10 @@ def _generate(self, step_name): for name, (tp, quals) in sorted(lst): kind, realname = name.split(' ', 1) try: - method = getattr(self, '_generate_cpy_%s_%s' % (kind, - step_name)) + method = getattr(self, f'_generate_cpy_{kind}_{step_name}') except AttributeError: raise VerificationError( - "not implemented in recompile(): %r" % name) + f"not implemented in recompile(): {name!r}") try: self._current_quals = quals method(tp, realname) @@ -319,16 +313,14 @@ def write_c_source_to_f(self, f, preamble): # and include an extra file base_module_name = self.module_name.split('.')[-1] if self.ffi._embedding is not None: - prnt('#define _CFFI_MODULE_NAME "%s"' % (self.module_name,)) + prnt(f'#define _CFFI_MODULE_NAME "{self.module_name}"') prnt('static const char _CFFI_PYTHON_STARTUP_CODE[] = {') self._print_string_literal_in_array(self.ffi._embedding) prnt('0 };') prnt('#ifdef PYPY_VERSION') - prnt('# define _CFFI_PYTHON_STARTUP_FUNC _cffi_pypyinit_%s' % ( - base_module_name,)) + prnt(f'# define _CFFI_PYTHON_STARTUP_FUNC _cffi_pypyinit_{base_module_name}') prnt('#else') - prnt('# define _CFFI_PYTHON_STARTUP_FUNC PyInit_%s' % ( - base_module_name,)) + prnt(f'# define _CFFI_PYTHON_STARTUP_FUNC PyInit_{base_module_name}') prnt('#endif') lines = self._rel_readlines('_embedding.h') i = lines.index('#include "_cffi_errors.h"\n') @@ -368,8 +360,7 @@ def write_c_source_to_f(self, f, preamble): lst = self._lsts[step_name] nums[step_name] = len(lst) if nums[step_name] > 0: - prnt('static const struct _cffi_%s_s _cffi_%ss[] = {' % ( - step_name, step_name)) + prnt(f'static const struct _cffi_{step_name}_s _cffi_{step_name}s[] = {{') for entry in lst: prnt(entry.as_c_expr()) prnt('};') @@ -384,14 +375,13 @@ def write_c_source_to_f(self, f, preamble): ffi_to_include._assigned_source[:2]) except AttributeError: raise VerificationError( - "ffi object %r includes %r, but the latter has not " - "been prepared with set_source()" % ( - self.ffi, ffi_to_include,)) + f"ffi object {self.ffi!r} includes {ffi_to_include!r}, but the latter has not " + "been prepared with set_source()") if included_source is None: raise VerificationError( "not implemented yet: ffi.include() of a Python-based " "ffi inside a C-based ffi") - prnt(' "%s",' % (included_module_name,)) + prnt(f' "{included_module_name}",') prnt(' NULL') prnt('};') prnt() @@ -401,9 +391,9 @@ def write_c_source_to_f(self, f, preamble): prnt(' _cffi_types,') for step_name in self.ALL_STEPS: if nums[step_name] > 0: - prnt(' _cffi_%ss,' % step_name) + prnt(f' _cffi_{step_name}s,') else: - prnt(' NULL, /* no %ss */' % step_name) + prnt(f' NULL, /* no {step_name}s */') for step_name in self.ALL_STEPS: if step_name != "field": prnt(' %d, /* num_%ss */' % (nums[step_name], step_name)) @@ -426,14 +416,14 @@ def write_c_source_to_f(self, f, preamble): prnt() prnt('#ifdef PYPY_VERSION') prnt('PyMODINIT_FUNC') - prnt('_cffi_pypyinit_%s(const void *p[])' % (base_module_name,)) + prnt(f'_cffi_pypyinit_{base_module_name}(const void *p[])') prnt('{') if flags & 1: prnt(' if (((intptr_t)p[0]) >= 0x0A03) {') prnt(' _cffi_call_python_org = ' '(void(*)(struct _cffi_externpy_s *, char *))p[1];') prnt(' }') - prnt(' p[0] = (const void *)0x%x;' % self._version) + prnt(f' p[0] = (const void *)0x{self._version:x};') prnt(' p[1] = &_cffi_type_context;') prnt(' return NULL;') prnt('}') @@ -442,14 +432,13 @@ def write_c_source_to_f(self, f, preamble): # give it one prnt('# ifdef _MSC_VER') prnt(' PyMODINIT_FUNC') - prnt(' PyInit_%s(void) { return NULL; }' % (base_module_name,)) + prnt(f' PyInit_{base_module_name}(void) {{ return NULL; }}') prnt('# endif') prnt('#else') prnt('PyMODINIT_FUNC') - prnt('PyInit_%s(void)' % (base_module_name,)) + prnt(f'PyInit_{base_module_name}(void)') prnt('{') - prnt(' return _cffi_init("%s", 0x%x, &_cffi_type_context);' % ( - self.module_name, self._version)) + prnt(f' return _cffi_init("{self.module_name}", 0x{self._version:x}, &_cffi_type_context);') prnt('}') prnt('#endif') prnt() @@ -460,12 +449,12 @@ def write_c_source_to_f(self, f, preamble): def _to_py(self, x): if isinstance(x, str): - return "b'%s'" % (x,) + return f"b'{x}'" if isinstance(x, (list, tuple)): rep = [self._to_py(item) for item in x] if len(rep) == 1: rep.append('') - return "(%s)" % (','.join(rep),) + return "({})".format(','.join(rep)) return x.as_python_expr() # Py2: unicode unexpected; Py3: bytes unexp. def write_py_source_to_f(self, f): @@ -485,34 +474,33 @@ def write_py_source_to_f(self, f): ffi_to_include._assigned_source[:2]) except AttributeError: raise VerificationError( - "ffi object %r includes %r, but the latter has not " - "been prepared with set_source()" % ( - self.ffi, ffi_to_include,)) + f"ffi object {self.ffi!r} includes {ffi_to_include!r}, but the latter has not " + "been prepared with set_source()") if included_source is not None: raise VerificationError( "not implemented yet: ffi.include() of a C-based " "ffi inside a Python-based ffi") prnt('from %s import ffi as _ffi%d' % (included_module_name, i)) prnt() - prnt("ffi = _cffi_backend.FFI('%s'," % (self.module_name,)) - prnt(" _version = 0x%x," % (self._version,)) + prnt(f"ffi = _cffi_backend.FFI('{self.module_name}',") + prnt(f" _version = 0x{self._version:x},") self._version = None # # the '_types' keyword argument self.cffi_types = tuple(self.cffi_types) # don't change any more types_lst = [op.as_python_bytes() for op in self.cffi_types] - prnt(' _types = %s,' % (self._to_py(''.join(types_lst)),)) + prnt(' _types = {},'.format(self._to_py(''.join(types_lst)))) typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()]) # # the keyword arguments from ALL_STEPS for step_name in self.ALL_STEPS: lst = self._lsts[step_name] if len(lst) > 0 and step_name != "field": - prnt(' _%ss = %s,' % (step_name, self._to_py(lst))) + prnt(f' _{step_name}s = {self._to_py(lst)},') # # the '_includes' keyword argument if num_includes > 0: - prnt(' _includes = (%s,),' % ( + prnt(' _includes = ({},),'.format( ', '.join(['_ffi%d' % i for i in range(num_includes)]),)) # # the footer @@ -529,14 +517,14 @@ def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode): if isinstance(tp, model.BasePrimitiveType) and not tp.is_complex_type(): if tp.is_integer_type() and tp.name != '_Bool': converter = '_cffi_to_c_int' - extraarg = ', %s' % tp.name + extraarg = f', {tp.name}' elif isinstance(tp, model.UnknownFloatType): # don't check with is_float_type(): it may be a 'long # double' here, and _cffi_to_c_double would loose precision - converter = '(%s)_cffi_to_c_double' % (tp.get_c_name(''),) + converter = '({})_cffi_to_c_double'.format(tp.get_c_name('')) else: cname = tp.get_c_name('') - converter = '(%s)_cffi_to_c_%s' % (cname, + converter = '({})_cffi_to_c_{}'.format(cname, tp.name.replace(' ', '_')) if cname in ('char16_t', 'char32_t'): self.needs_version(VERSION_CHAR16CHAR32) @@ -552,21 +540,21 @@ def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode): # or, a complex (the same code works) self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)' % (tovar, self._gettypenum(tp), fromvar)) - self._prnt(' %s;' % errcode) + self._prnt(f' {errcode};') return # elif isinstance(tp, model.FunctionPtrType): - converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('') + converter = '({})_cffi_to_c_pointer'.format(tp.get_c_name('')) extraarg = ', _cffi_type(%d)' % self._gettypenum(tp) errvalue = 'NULL' # else: raise NotImplementedError(tp) # - self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg)) - self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % ( + self._prnt(f' {tovar} = {converter}({fromvar}{extraarg});') + self._prnt(' if ({} == ({}){} && PyErr_Occurred())'.format( tovar, tp.get_c_name(''), errvalue)) - self._prnt(' %s;' % errcode) + self._prnt(f' {errcode};') def _extra_local_variables(self, tp, localvars, freelines): if isinstance(tp, model.PointerType): @@ -580,26 +568,26 @@ def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode): self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % ( self._gettypenum(tp), fromvar, tovar)) self._prnt(' if (datasize != 0) {') - self._prnt(' %s = ((size_t)datasize) <= 640 ? ' - '(%s)alloca((size_t)datasize) : NULL;' % ( + self._prnt(' {} = ((size_t)datasize) <= 640 ? ' + '({})alloca((size_t)datasize) : NULL;'.format( tovar, tp.get_c_name(''))) self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, ' '(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar)) self._prnt(' datasize, &large_args_free) < 0)') - self._prnt(' %s;' % errcode) + self._prnt(f' {errcode};') self._prnt(' }') def _convert_expr_from_c(self, tp, var, context): if isinstance(tp, model.BasePrimitiveType): if tp.is_integer_type() and tp.name != '_Bool': - return '_cffi_from_c_int(%s, %s)' % (var, tp.name) + return f'_cffi_from_c_int({var}, {tp.name})' elif isinstance(tp, model.UnknownFloatType): - return '_cffi_from_c_double(%s)' % (var,) + return f'_cffi_from_c_double({var})' elif tp.name != 'long double' and not tp.is_complex_type(): cname = tp.name.replace(' ', '_') if cname in ('char16_t', 'char32_t'): self.needs_version(VERSION_CHAR16CHAR32) - return '_cffi_from_c_%s(%s)' % (cname, var) + return f'_cffi_from_c_{cname}({var})' else: return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( var, self._gettypenum(tp)) @@ -611,8 +599,7 @@ def _convert_expr_from_c(self, tp, var, context): var, self._gettypenum(model.PointerType(tp.item))) elif isinstance(tp, model.StructOrUnion): if tp.fldnames is None: - raise TypeError("'%s' is used as %s, but is opaque" % ( - tp._get_c_name(), context)) + raise TypeError(f"'{tp._get_c_name()}' is used as {context}, but is opaque") return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % ( var, self._gettypenum(tp)) elif isinstance(tp, model.EnumType): @@ -625,7 +612,7 @@ def _convert_expr_from_c(self, tp, var, context): # typedefs def _typedef_type(self, tp, name): - return self._global_type(tp, "(*(%s *)0)" % (name,)) + return self._global_type(tp, f"(*({name} *)0)") def _generate_cpy_typedef_collecttype(self, tp, name): self._do_collect_type(self._typedef_type(tp, name)) @@ -676,7 +663,7 @@ def _generate_cpy_function_decl(self, tp, name): # the 'd' version of the function, only for addressof(lib, 'func') arguments = [] call_arguments = [] - context = 'argument of %s' % name + context = f'argument of {name}' for i, type in enumerate(tp.args): arguments.append(type.get_c_name(' x%d' % i, context)) call_arguments.append('x%d' % i) @@ -686,38 +673,38 @@ def _generate_cpy_function_decl(self, tp, name): abi = tp.abi + ' ' else: abi = '' - name_and_arguments = '%s_cffi_d_%s(%s)' % (abi, name, repr_arguments) - prnt('static %s' % (tp.result.get_c_name(name_and_arguments),)) + name_and_arguments = f'{abi}_cffi_d_{name}({repr_arguments})' + prnt(f'static {tp.result.get_c_name(name_and_arguments)}') prnt('{') call_arguments = ', '.join(call_arguments) result_code = 'return ' if isinstance(tp.result, model.VoidType): result_code = '' - prnt(' %s%s(%s);' % (result_code, name, call_arguments)) + prnt(f' {result_code}{name}({call_arguments});') prnt('}') # prnt('#ifndef PYPY_VERSION') # ------------------------------ # prnt('static PyObject *') - prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname)) + prnt(f'_cffi_f_{name}(PyObject *self, PyObject *{argname})') prnt('{') # - context = 'argument of %s' % name + context = f'argument of {name}' for i, type in enumerate(tp.args): arg = type.get_c_name(' x%d' % i, context) - prnt(' %s;' % arg) + prnt(f' {arg};') # localvars = set() freelines = set() for type in tp.args: self._extra_local_variables(type, localvars, freelines) for decl in sorted(localvars): - prnt(' %s;' % (decl,)) + prnt(f' {decl};') # if not isinstance(tp.result, model.VoidType): result_code = 'result = ' - context = 'result of %s' % name - result_decl = ' %s;' % tp.result.get_c_name(' result', context) + context = f'result of {name}' + result_decl = ' {};'.format(tp.result.get_c_name(' result', context)) prnt(result_decl) prnt(' PyObject *pyresult;') else: @@ -744,7 +731,7 @@ def _generate_cpy_function_decl(self, tp, name): prnt(' _cffi_restore_errno();') call_arguments = ['x%d' % i for i in range(len(tp.args))] call_arguments = ', '.join(call_arguments) - prnt(' { %s%s(%s); }' % (result_code, name, call_arguments)) + prnt(f' {{ {result_code}{name}({call_arguments}); }}') prnt(' _cffi_save_errno();') prnt(' Py_END_ALLOW_THREADS') prnt() @@ -753,8 +740,7 @@ def _generate_cpy_function_decl(self, tp, name): if numargs == 0: prnt(' (void)noarg; /* unused */') if result_code: - prnt(' pyresult = %s;' % - self._convert_expr_from_c(tp.result, 'result', 'result type')) + prnt(' pyresult = {};'.format(self._convert_expr_from_c(tp.result, 'result', 'result type'))) for freeline in freelines: prnt(' ' + freeline) prnt(' return pyresult;') @@ -778,7 +764,7 @@ def need_indirection(type): difference = False arguments = [] call_arguments = [] - context = 'argument of %s' % name + context = f'argument of {name}' for i, type in enumerate(tp.args): indirection = '' if need_indirection(type): @@ -789,7 +775,7 @@ def need_indirection(type): call_arguments.append('%sx%d' % (indirection, i)) tp_result = tp.result if need_indirection(tp_result): - context = 'result of %s' % name + context = f'result of {name}' arg = tp_result.get_c_name(' *result', context) arguments.insert(0, arg) tp_result = model.void_type @@ -799,19 +785,18 @@ def need_indirection(type): if difference: repr_arguments = ', '.join(arguments) repr_arguments = repr_arguments or 'void' - name_and_arguments = '%s_cffi_f_%s(%s)' % (abi, name, - repr_arguments) - prnt('static %s' % (tp_result.get_c_name(name_and_arguments),)) + name_and_arguments = f'{abi}_cffi_f_{name}({repr_arguments})' + prnt(f'static {tp_result.get_c_name(name_and_arguments)}') prnt('{') if result_decl: prnt(result_decl) call_arguments = ', '.join(call_arguments) - prnt(' { %s%s(%s); }' % (result_code, name, call_arguments)) + prnt(f' {{ {result_code}{name}({call_arguments}); }}') if result_decl: prnt(' return result;') prnt('}') else: - prnt('# define _cffi_f_%s _cffi_d_%s' % (name, name)) + prnt(f'# define _cffi_f_{name} _cffi_d_{name}') # prnt('#endif') # ------------------------------ prnt() @@ -831,9 +816,9 @@ def _generate_cpy_function_ctx(self, tp, name): else: meth_kind = OP_CPYTHON_BLTN_V # 'METH_VARARGS' self._lsts["global"].append( - GlobalExpr(name, '_cffi_f_%s' % name, + GlobalExpr(name, f'_cffi_f_{name}', CffiOp(meth_kind, type_index), - size='_cffi_d_%s' % name)) + size=f'_cffi_d_{name}')) # ---------- # named structs or unions @@ -843,9 +828,8 @@ def _field_type(self, tp_struct, field_name, tp_field): actual_length = tp_field.length if actual_length == '...': ptr_struct_name = tp_struct.get_c_name('*') - actual_length = '_cffi_array_len(((%s)0)->%s)' % ( - ptr_struct_name, field_name) - tp_item = self._field_type(tp_struct, '%s[0]' % field_name, + actual_length = f'_cffi_array_len((({ptr_struct_name})0)->{field_name})' + tp_item = self._field_type(tp_struct, f'{field_name}[0]', tp_field.item) tp_field = model.ArrayType(tp_item, actual_length) return tp_field @@ -861,9 +845,9 @@ def _struct_decl(self, tp, cname, approxname): if tp.fldtypes is None: return prnt = self._prnt - checkfuncname = '_cffi_checkfld_%s' % (approxname,) + checkfuncname = f'_cffi_checkfld_{approxname}' prnt('_CFFI_UNUSED_FN') - prnt('static void %s(%s *p)' % (checkfuncname, cname)) + prnt(f'static void {checkfuncname}({cname} *p)') prnt('{') prnt(' /* only to generate compile-time warnings or errors */') prnt(' (void)p;') @@ -872,8 +856,8 @@ def _struct_decl(self, tp, cname, approxname): if ftype.is_integer_type() or fbitsize >= 0: # accept all integers, but complain on float or double if fname != '': - prnt(" (void)((p->%s) | 0); /* check that '%s.%s' is " - "an integer */" % (fname, cname, fname)) + prnt(f" (void)((p->{fname}) | 0); /* check that '{cname}.{fname}' is " + "an integer */") continue # only accept exactly the type declared, except that '[]' # is interpreted as a '*' and so will match any array length. @@ -882,13 +866,13 @@ def _struct_decl(self, tp, cname, approxname): and (ftype.length is None or ftype.length == '...')): ftype = ftype.item fname = fname + '[0]' - prnt(' { %s = &p->%s; (void)tmp; }' % ( - ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual), + prnt(' {{ {} = &p->{}; (void)tmp; }}'.format( + ftype.get_c_name('*tmp', f'field {fname!r}', quals=fqual), fname)) except VerificationError as e: - prnt(' /* %s */' % str(e)) # cannot verify it, ignore + prnt(f' /* {str(e)} */') # cannot verify it, ignore prnt('}') - prnt('struct _cffi_align_%s { char x; %s y; };' % (approxname, cname)) + prnt(f'struct _cffi_align_{approxname} {{ char x; {cname} y; }};') prnt() def _struct_ctx(self, tp, cname, approxname, named_ptr=None): @@ -912,10 +896,9 @@ def _struct_ctx(self, tp, cname, approxname, named_ptr=None): if tp.packed: if tp.packed > 1: raise NotImplementedError( - "%r is declared with 'pack=%r'; only 0 or 1 are " + f"{tp!r} is declared with 'pack={tp.packed!r}'; only 0 or 1 are " "supported in API mode (try to use \"...;\", which " - "does not require a 'pack' declaration)" % - (tp, tp.packed)) + "does not require a 'pack' declaration)") flags.append("_CFFI_F_PACKED") else: flags.append("_CFFI_F_EXTERNAL") @@ -927,7 +910,7 @@ def _struct_ctx(self, tp, cname, approxname, named_ptr=None): for fldname, fldtype, fbitsize, fqual in enumfields: fldtype = self._field_type(tp, fldname, fldtype) self._check_not_opaque(fldtype, - "field '%s.%s'" % (tp.name, fldname)) + f"field '{tp.name}.{fldname}'") # cname is None for _add_missing_struct_unions() only op = OP_NOOP if fbitsize >= 0: @@ -938,17 +921,16 @@ def _struct_ctx(self, tp, cname, approxname, named_ptr=None): fldtype.length is None): size = '(size_t)-1' else: - size = 'sizeof(((%s)0)->%s)' % ( + size = 'sizeof((({})0)->{})'.format( tp.get_c_name('*') if named_ptr is None else named_ptr.name, fldname) if cname is None or fbitsize >= 0: offset = '(size_t)-1' elif named_ptr is not None: - offset = '(size_t)(((char *)&((%s)4096)->%s) - (char *)4096)' % ( - named_ptr.name, fldname) + offset = f'(size_t)(((char *)&(({named_ptr.name})4096)->{fldname}) - (char *)4096)' else: - offset = 'offsetof(%s, %s)' % (tp.get_c_name(''), fldname) + offset = 'offsetof({}, {})'.format(tp.get_c_name(''), fldname) c_fields.append( FieldExpr(fldname, offset, size, fbitsize, CffiOp(op, self._typesdict[fldtype]))) @@ -961,11 +943,11 @@ def _struct_ctx(self, tp, cname, approxname, named_ptr=None): comment = "unnamed" else: if named_ptr is not None: - size = 'sizeof(*(%s)0)' % (named_ptr.name,) + size = f'sizeof(*({named_ptr.name})0)' align = '-1 /* unknown alignment */' else: - size = 'sizeof(%s)' % (cname,) - align = 'offsetof(struct _cffi_align_%s, y)' % (approxname,) + size = f'sizeof({cname})' + align = f'offsetof(struct _cffi_align_{approxname}, y)' comment = None else: size = '(size_t)-1' @@ -982,7 +964,7 @@ def _check_not_opaque(self, tp, location): tp = tp.item if isinstance(tp, model.StructOrUnion) and tp.fldtypes is None: raise TypeError( - "%s is of an opaque type (not declared in cdef())" % location) + f"{location} is of an opaque type (not declared in cdef())") def _add_missing_struct_unions(self): # not very nice, but some struct declarations might be missing @@ -994,17 +976,16 @@ def _add_missing_struct_unions(self): for tp, order in lst: if tp not in self._seen_struct_unions: if tp.partial: - raise NotImplementedError("internal inconsistency: %r is " + raise NotImplementedError(f"internal inconsistency: {tp!r} is " "partial but was not seen at " - "this point" % (tp,)) + "this point") if tp.name.startswith('$') and tp.name[1:].isdigit(): approxname = tp.name[1:] elif tp.name == '_IO_FILE' and tp.forcename == 'FILE': approxname = 'FILE' self._typedef_ctx(tp, 'FILE') else: - raise NotImplementedError("internal inconsistency: %r" % - (tp,)) + raise NotImplementedError(f"internal inconsistency: {tp!r}") self._struct_ctx(tp, None, approxname) def _generate_cpy_struct_collecttype(self, tp, name): @@ -1055,29 +1036,29 @@ def _generate_cpy_const(self, is_int, name, tp=None, category='const', check_value=None): if (category, name) in self._seen_constants: raise VerificationError( - "duplicate declaration of %s '%s'" % (category, name)) + f"duplicate declaration of {category} '{name}'") self._seen_constants.add((category, name)) # prnt = self._prnt - funcname = '_cffi_%s_%s' % (category, name) + funcname = f'_cffi_{category}_{name}' if is_int: - prnt('static int %s(unsigned long long *o)' % funcname) + prnt(f'static int {funcname}(unsigned long long *o)') prnt('{') - prnt(' int n = (%s) <= 0;' % (name,)) - prnt(' *o = (unsigned long long)((%s) | 0);' - ' /* check that %s is an integer */' % (name, name)) + prnt(f' int n = ({name}) <= 0;') + prnt(f' *o = (unsigned long long)(({name}) | 0);' + f' /* check that {name} is an integer */') if check_value is not None: if check_value > 0: check_value = '%dU' % (check_value,) - prnt(' if (!_cffi_check_int(*o, n, %s))' % (check_value,)) + prnt(f' if (!_cffi_check_int(*o, n, {check_value}))') prnt(' n |= 2;') prnt(' return n;') prnt('}') else: assert check_value is None - prnt('static void %s(char *o)' % funcname) + prnt(f'static void {funcname}(char *o)') prnt('{') - prnt(' *(%s)o = %s;' % (tp.get_c_name('*'), name)) + prnt(' *({})o = {};'.format(tp.get_c_name('*'), name)) prnt('}') prnt() @@ -1101,7 +1082,7 @@ def _generate_cpy_constant_ctx(self, tp, name): type_index = self._typesdict[tp] type_op = CffiOp(const_kind, type_index) self._lsts["global"].append( - GlobalExpr(name, '_cffi_const_%s' % name, type_op)) + GlobalExpr(name, f'_cffi_const_{name}', type_op)) # ---------- # enums @@ -1120,12 +1101,12 @@ def _enum_ctx(self, tp, cname): tp.check_not_partial() for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): self._lsts["global"].append( - GlobalExpr(enumerator, '_cffi_const_%s' % enumerator, type_op, + GlobalExpr(enumerator, f'_cffi_const_{enumerator}', type_op, check_value=enumvalue)) # if cname is not None and '$' not in cname and not self.target_is_python: - size = "sizeof(%s)" % cname - signed = "((%s)-1) <= 0" % cname + size = f"sizeof({cname})" + signed = f"(({cname})-1) <= 0" else: basetp = tp.build_baseinttype(self.ffi, []) size = self.ffi.sizeof(basetp) @@ -1154,14 +1135,14 @@ def _generate_cpy_macro_ctx(self, tp, name): if tp == '...': if self.target_is_python: raise VerificationError( - "cannot use the syntax '...' in '#define %s ...' when " - "using the ABI mode" % (name,)) + f"cannot use the syntax '...' in '#define {name} ...' when " + "using the ABI mode") check_value = None else: check_value = tp # an integer type_op = CffiOp(OP_CONSTANT_INT, -1) self._lsts["global"].append( - GlobalExpr(name, '_cffi_const_%s' % name, type_op, + GlobalExpr(name, f'_cffi_const_{name}', type_op, check_value=check_value)) # ---------- @@ -1171,8 +1152,8 @@ def _global_type(self, tp, global_name): if isinstance(tp, model.ArrayType): actual_length = tp.length if actual_length == '...': - actual_length = '_cffi_array_len(%s)' % (global_name,) - tp_item = self._global_type(tp.item, '%s[0]' % global_name) + actual_length = f'_cffi_array_len({global_name})' + tp_item = self._global_type(tp.item, f'{global_name}[0]') tp = model.ArrayType(tp_item, actual_length) return tp @@ -1195,10 +1176,10 @@ def _generate_cpy_variable_decl(self, tp, name): # if 'tp' were a function type, but that is not possible here. # (If 'tp' is a function _pointer_ type, then casts from "fn_t # **" to "void *" are again no-ops, as far as I can tell.) - decl = '*_cffi_var_%s(void)' % (name,) + decl = f'*_cffi_var_{name}(void)' prnt('static ' + tp.get_c_name(decl, quals=self._current_quals)) prnt('{') - prnt(' return %s(%s);' % (ampersand, name)) + prnt(f' return {ampersand}({name});') prnt('}') prnt() @@ -1210,7 +1191,7 @@ def _generate_cpy_variable_ctx(self, tp, name): else: op = OP_GLOBAL_VAR_F self._lsts["global"].append( - GlobalExpr(name, '_cffi_var_%s' % name, CffiOp(op, type_index))) + GlobalExpr(name, f'_cffi_var_{name}', CffiOp(op, type_index))) # ---------- # extern "Python" @@ -1227,23 +1208,22 @@ def _extern_python_decl(self, tp, name, tag_and_space): if isinstance(tp.result, model.VoidType): size_of_result = '0' else: - context = 'result of %s' % name - size_of_result = '(int)sizeof(%s)' % ( + context = f'result of {name}' + size_of_result = '(int)sizeof({})'.format( tp.result.get_c_name('', context),) - prnt('static struct _cffi_externpy_s _cffi_externpy__%s =' % name) - prnt(' { "%s.%s", %s, 0, 0 };' % ( - self.module_name, name, size_of_result)) + prnt(f'static struct _cffi_externpy_s _cffi_externpy__{name} =') + prnt(f' {{ "{self.module_name}.{name}", {size_of_result}, 0, 0 }};') prnt() # arguments = [] - context = 'argument of %s' % name + context = f'argument of {name}' for i, type in enumerate(tp.args): arg = type.get_c_name(' a%d' % i, context) arguments.append(arg) # repr_arguments = ', '.join(arguments) repr_arguments = repr_arguments or 'void' - name_and_arguments = '%s(%s)' % (name, repr_arguments) + name_and_arguments = f'{name}({repr_arguments})' if tp.abi == "__stdcall": name_and_arguments = '_cffi_stdcall ' + name_and_arguments # @@ -1258,9 +1238,9 @@ def may_need_128_bits(tp): size_of_a = 'sizeof(%s) > %d ? sizeof(%s) : %d' % ( tp.result.get_c_name(''), size_of_a, tp.result.get_c_name(''), size_of_a) - prnt('%s%s' % (tag_and_space, tp.result.get_c_name(name_and_arguments))) + prnt(f'{tag_and_space}{tp.result.get_c_name(name_and_arguments)}') prnt('{') - prnt(' char a[%s];' % size_of_a) + prnt(f' char a[{size_of_a}];') prnt(' char *p = a;') for i, type in enumerate(tp.args): arg = 'a%d' % i @@ -1269,9 +1249,9 @@ def may_need_128_bits(tp): arg = '&' + arg type = model.PointerType(type) prnt(' *(%s)(p + %d) = %s;' % (type.get_c_name('*'), i*8, arg)) - prnt(' _cffi_call_python(&_cffi_externpy__%s, p);' % name) + prnt(f' _cffi_call_python(&_cffi_externpy__{name}, p);') if not isinstance(tp.result, model.VoidType): - prnt(' return *(%s)p;' % (tp.result.get_c_name('*'),)) + prnt(' return *({})p;'.format(tp.result.get_c_name('*'))) prnt('}') prnt() self._num_externpy += 1 @@ -1294,7 +1274,7 @@ def _generate_cpy_extern_python_ctx(self, tp, name): type_index = self._typesdict[tp] type_op = CffiOp(OP_EXTERN_PYTHON, type_index) self._lsts["global"].append( - GlobalExpr(name, '&_cffi_externpy__%s' % name, type_op, name)) + GlobalExpr(name, f'&_cffi_externpy__{name}', type_op, name)) _generate_cpy_dllexport_python_ctx = \ _generate_cpy_extern_python_plus_c_ctx = \ @@ -1334,15 +1314,15 @@ def _emit_bytecode_PrimitiveType(self, tp, index): self.cffi_types[index] = CffiOp(OP_PRIMITIVE, prim_index) def _emit_bytecode_UnknownIntegerType(self, tp, index): - s = ('_cffi_prim_int(sizeof(%s), (\n' - ' ((%s)-1) | 0 /* check that %s is an integer type */\n' - ' ) <= 0)' % (tp.name, tp.name, tp.name)) + s = (f'_cffi_prim_int(sizeof({tp.name}), (\n' + f' (({tp.name})-1) | 0 /* check that {tp.name} is an integer type */\n' + ' ) <= 0)') self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s) def _emit_bytecode_UnknownFloatType(self, tp, index): - s = ('_cffi_prim_float(sizeof(%s) *\n' - ' (((%s)1) / 2) * 2 /* integer => 0, float => 1 */\n' - ' )' % (tp.name, tp.name)) + s = (f'_cffi_prim_float(sizeof({tp.name}) *\n' + f' ((({tp.name})1) / 2) * 2 /* integer => 0, float => 1 */\n' + ' )') self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s) def _emit_bytecode_RawFunctionType(self, tp, index): @@ -1361,7 +1341,7 @@ def _emit_bytecode_RawFunctionType(self, tp, index): if tp.abi == '__stdcall': flags |= 2 else: - raise NotImplementedError("abi=%r" % (tp.abi,)) + raise NotImplementedError(f"abi={tp.abi!r}") self.cffi_types[index] = CffiOp(OP_FUNCTION_END, flags) def _emit_bytecode_PointerType(self, tp, index): @@ -1380,8 +1360,8 @@ def _emit_bytecode_ArrayType(self, tp, index): self.cffi_types[index] = CffiOp(OP_OPEN_ARRAY, item_index) elif tp.length == '...': raise VerificationError( - "type %s badly placed: the '...' array length can only be " - "used on global arrays or on fields of structures" % ( + "type {} badly placed: the '...' array length can only be " + "used on global arrays or on fields of structures".format( str(tp).replace('/*...*/', '...'),)) else: assert self.cffi_types[index + 1] == 'LEN' @@ -1413,7 +1393,7 @@ def _is_file_like(maybefile): def _make_c_or_py_source(ffi, module_name, preamble, target_file, verbose): if verbose: - print("generating %s" % (target_file,)) + print(f"generating {target_file}") recompiler = Recompiler(ffi, module_name, target_is_python=(preamble is None)) recompiler.collect_type_table() @@ -1541,7 +1521,7 @@ def recompile(ffi, module_name, preamble, tmpdir='.', call_c_compiler=True, # if target is None: if embedding: - target = '%s.*' % module_name + target = f'{module_name}.*' else: target = '*' # @@ -1564,7 +1544,7 @@ def recompile(ffi, module_name, preamble, tmpdir='.', call_c_compiler=True, msg = 'the current directory is' else: msg = 'setting the current directory to' - print('%s %r' % (msg, os.path.abspath(tmpdir))) + print(f'{msg} {os.path.abspath(tmpdir)!r}') os.chdir(tmpdir) outputfilename = ffiplatform.compile('.', ext, compiler_verbose, debug) diff --git a/src/cffi/setuptools_ext.py b/src/cffi/setuptools_ext.py index 946afb45a..62d3a7ace 100644 --- a/src/cffi/setuptools_ext.py +++ b/src/cffi/setuptools_ext.py @@ -31,20 +31,19 @@ def add_cffi_module(dist, mod_spec): if not isinstance(mod_spec, basestring): error("argument to 'cffi_modules=...' must be a str or a list of str," - " not %r" % (type(mod_spec).__name__,)) + f" not {type(mod_spec).__name__!r}") mod_spec = str(mod_spec) try: build_file_name, ffi_var_name = mod_spec.split(':') except ValueError: - error("%r must be of the form 'path/build.py:ffi_variable'" % - (mod_spec,)) + error(f"{mod_spec!r} must be of the form 'path/build.py:ffi_variable'") if not os.path.exists(build_file_name): ext = '' rewritten = build_file_name.replace('.', '/') + '.py' if os.path.exists(rewritten): - ext = ' (rewrite cffi_modules to [%r])' % ( + ext = ' (rewrite cffi_modules to [{!r}])'.format( rewritten + ':' + ffi_var_name,) - error("%r does not name an existing file%s" % (build_file_name, ext)) + error(f"{build_file_name!r} does not name an existing file{ext}") mod_vars = {'__name__': '__cffi__', '__file__': build_file_name} execfile(build_file_name, mod_vars) @@ -52,15 +51,13 @@ def add_cffi_module(dist, mod_spec): try: ffi = mod_vars[ffi_var_name] except KeyError: - error("%r: object %r not found in module" % (mod_spec, - ffi_var_name)) + error(f"{mod_spec!r}: object {ffi_var_name!r} not found in module") if not isinstance(ffi, FFI): ffi = ffi() # maybe it's a function instead of directly an ffi if not isinstance(ffi, FFI): - error("%r is not an FFI instance (got %r)" % (mod_spec, - type(ffi).__name__)) + error(f"{mod_spec!r} is not an FFI instance (got {type(ffi).__name__!r})") if not hasattr(ffi, '_assigned_source'): - error("%r: the set_source() method was not called" % (mod_spec,)) + error(f"{mod_spec!r}: the set_source() method was not called") module_name, source, source_extension, kwds = ffi._assigned_source if ffi._windows_unicode: kwds = kwds.copy() @@ -131,7 +128,7 @@ def _add_c_module(dist, ffi, module_name, source, source_extension, kwds): def make_mod(tmpdir, pre_run=None): c_file = os.path.join(tmpdir, module_name + source_extension) - log.info("generating cffi module %r" % c_file) + log.info(f"generating cffi module {c_file!r}") mkpath(tmpdir) # a setuptools-only, API-only hook: called with the "ext" and "ffi" # arguments just before we turn the ffi into C code. To use it, @@ -169,7 +166,7 @@ def _add_py_module(dist, ffi, module_name): from cffi import recompiler def generate_mod(py_file): - log.info("generating cffi module %r" % py_file) + log.info(f"generating cffi module {py_file!r}") mkpath(os.path.dirname(py_file)) updated = recompiler.make_py_source(ffi, module_name, py_file) if not updated: diff --git a/src/cffi/vengine_cpy.py b/src/cffi/vengine_cpy.py index 4d2ea43e5..0c38e9510 100644 --- a/src/cffi/vengine_cpy.py +++ b/src/cffi/vengine_cpy.py @@ -104,7 +104,7 @@ def write_source_to_f(self): constants = self._chained_list_constants[False] prnt('static struct PyModuleDef _cffi_module_def = {') prnt(' PyModuleDef_HEAD_INIT,') - prnt(' "%s",' % modname) + prnt(f' "{modname}",') prnt(' NULL,') prnt(' -1,') prnt(' _cffi_methods,') @@ -112,13 +112,13 @@ def write_source_to_f(self): prnt('};') prnt() prnt('PyMODINIT_FUNC') - prnt('PyInit_%s(void)' % modname) + prnt(f'PyInit_{modname}(void)') prnt('{') prnt(' PyObject *lib;') prnt(' lib = PyModule_Create(&_cffi_module_def);') prnt(' if (lib == NULL)') prnt(' return NULL;') - prnt(' if (%s < 0 || _cffi_init() < 0) {' % (constants,)) + prnt(f' if ({constants} < 0 || _cffi_init() < 0) {{') prnt(' Py_DECREF(lib);') prnt(' return NULL;') prnt(' }') @@ -142,7 +142,7 @@ def load_library(self, flags=None): module = imp.load_dynamic(self.verifier.get_module_name(), self.verifier.modulefilename) except ImportError as e: - error = "importing %r: %s" % (self.verifier.modulefilename, e) + error = f"importing {self.verifier.modulefilename!r}: {e}" raise VerificationError(error) finally: if hasattr(sys, "setdlopenflags"): @@ -175,8 +175,7 @@ def __dir__(self): library = FFILibrary() if module._cffi_setup(lst, VerificationError, library): import warnings - warnings.warn("reimporting %r might overwrite older definitions" - % (self.verifier.get_module_name())) + warnings.warn(f"reimporting {self.verifier.get_module_name()!r} might overwrite older definitions") # # finally, call the loaded_cpy_xxx() functions. This will perform # the final adjustments, like copying the Python->C wrapper @@ -197,11 +196,10 @@ def _generate(self, step_name): for name, tp in self._get_declarations(): kind, realname = name.split(' ', 1) try: - method = getattr(self, '_generate_cpy_%s_%s' % (kind, - step_name)) + method = getattr(self, f'_generate_cpy_{kind}_{step_name}') except AttributeError: raise VerificationError( - "not implemented in verify(): %r" % name) + f"not implemented in verify(): {name!r}") try: method(tp, realname) except Exception as e: @@ -211,7 +209,7 @@ def _generate(self, step_name): def _load(self, module, step_name, **kwds): for name, tp in self._get_declarations(): kind, realname = name.split(' ', 1) - method = getattr(self, '_%s_cpy_%s' % (step_name, kind)) + method = getattr(self, f'_{step_name}_cpy_{kind}') try: method(tp, realname, module, **kwds) except Exception as e: @@ -231,12 +229,12 @@ def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode): if isinstance(tp, model.PrimitiveType): if tp.is_integer_type() and tp.name != '_Bool': converter = '_cffi_to_c_int' - extraarg = ', %s' % tp.name + extraarg = f', {tp.name}' elif tp.is_complex_type(): raise VerificationError( "not implemented in verify(): complex types") else: - converter = '(%s)_cffi_to_c_%s' % (tp.get_c_name(''), + converter = '({})_cffi_to_c_{}'.format(tp.get_c_name(''), tp.name.replace(' ', '_')) errvalue = '-1' # @@ -249,21 +247,21 @@ def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode): # a struct (not a struct pointer) as a function argument self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)' % (tovar, self._gettypenum(tp), fromvar)) - self._prnt(' %s;' % errcode) + self._prnt(f' {errcode};') return # elif isinstance(tp, model.FunctionPtrType): - converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('') + converter = '({})_cffi_to_c_pointer'.format(tp.get_c_name('')) extraarg = ', _cffi_type(%d)' % self._gettypenum(tp) errvalue = 'NULL' # else: raise NotImplementedError(tp) # - self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg)) - self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % ( + self._prnt(f' {tovar} = {converter}({fromvar}{extraarg});') + self._prnt(' if ({} == ({}){} && PyErr_Occurred())'.format( tovar, tp.get_c_name(''), errvalue)) - self._prnt(' %s;' % errcode) + self._prnt(f' {errcode};') def _extra_local_variables(self, tp, localvars, freelines): if isinstance(tp, model.PointerType): @@ -277,20 +275,20 @@ def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode): self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % ( self._gettypenum(tp), fromvar, tovar)) self._prnt(' if (datasize != 0) {') - self._prnt(' %s = ((size_t)datasize) <= 640 ? ' - 'alloca((size_t)datasize) : NULL;' % (tovar,)) + self._prnt(f' {tovar} = ((size_t)datasize) <= 640 ? ' + 'alloca((size_t)datasize) : NULL;') self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, ' '(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar)) self._prnt(' datasize, &large_args_free) < 0)') - self._prnt(' %s;' % errcode) + self._prnt(f' {errcode};') self._prnt(' }') def _convert_expr_from_c(self, tp, var, context): if isinstance(tp, model.PrimitiveType): if tp.is_integer_type() and tp.name != '_Bool': - return '_cffi_from_c_int(%s, %s)' % (var, tp.name) + return f'_cffi_from_c_int({var}, {tp.name})' elif tp.name != 'long double': - return '_cffi_from_c_%s(%s)' % (tp.name.replace(' ', '_'), var) + return '_cffi_from_c_{}({})'.format(tp.name.replace(' ', '_'), var) else: return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( var, self._gettypenum(tp)) @@ -302,8 +300,7 @@ def _convert_expr_from_c(self, tp, var, context): var, self._gettypenum(model.PointerType(tp.item))) elif isinstance(tp, model.StructOrUnion): if tp.fldnames is None: - raise TypeError("'%s' is used as %s, but is opaque" % ( - tp._get_c_name(), context)) + raise TypeError(f"'{tp._get_c_name()}' is used as {context}, but is opaque") return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % ( var, self._gettypenum(tp)) elif isinstance(tp, model.EnumType): @@ -352,24 +349,24 @@ def _generate_cpy_function_decl(self, tp, name): else: argname = 'args' prnt('static PyObject *') - prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname)) + prnt(f'_cffi_f_{name}(PyObject *self, PyObject *{argname})') prnt('{') # - context = 'argument of %s' % name + context = f'argument of {name}' for i, type in enumerate(tp.args): - prnt(' %s;' % type.get_c_name(' x%d' % i, context)) + prnt(' {};'.format(type.get_c_name(' x%d' % i, context))) # localvars = set() freelines = set() for type in tp.args: self._extra_local_variables(type, localvars, freelines) for decl in sorted(localvars): - prnt(' %s;' % (decl,)) + prnt(f' {decl};') # if not isinstance(tp.result, model.VoidType): result_code = 'result = ' - context = 'result of %s' % name - prnt(' %s;' % tp.result.get_c_name(' result', context)) + context = f'result of {name}' + prnt(' {};'.format(tp.result.get_c_name(' result', context))) prnt(' PyObject *pyresult;') else: result_code = '' @@ -379,7 +376,7 @@ def _generate_cpy_function_decl(self, tp, name): for i in rng: prnt(' PyObject *arg%d;' % i) prnt() - prnt(' if (!PyArg_ParseTuple(args, "%s:%s", %s))' % ( + prnt(' if (!PyArg_ParseTuple(args, "{}:{}", {}))'.format( 'O' * numargs, name, ', '.join(['&arg%d' % i for i in rng]))) prnt(' return NULL;') prnt() @@ -391,7 +388,7 @@ def _generate_cpy_function_decl(self, tp, name): # prnt(' Py_BEGIN_ALLOW_THREADS') prnt(' _cffi_restore_errno();') - prnt(' { %s%s(%s); }' % ( + prnt(' {{ {}{}({}); }}'.format( result_code, name, ', '.join(['x%d' % i for i in range(len(tp.args))]))) prnt(' _cffi_save_errno();') @@ -402,8 +399,7 @@ def _generate_cpy_function_decl(self, tp, name): if numargs == 0: prnt(' (void)noarg; /* unused */') if result_code: - prnt(' pyresult = %s;' % - self._convert_expr_from_c(tp.result, 'result', 'result type')) + prnt(' pyresult = {};'.format(self._convert_expr_from_c(tp.result, 'result', 'result type'))) for freeline in freelines: prnt(' ' + freeline) prnt(' return pyresult;') @@ -425,7 +421,7 @@ def _generate_cpy_function_method(self, tp, name): meth = 'METH_O' else: meth = 'METH_VARARGS' - self._prnt(' {"%s", _cffi_f_%s, %s, NULL},' % (name, name, meth)) + self._prnt(f' {{"{name}", _cffi_f_{name}, {meth}, NULL}},') _loading_cpy_function = _loaded_noop @@ -464,12 +460,12 @@ def _loaded_cpy_union(self, tp, name, module, **kwds): def _generate_struct_or_union_decl(self, tp, prefix, name): if tp.fldnames is None: return # nothing to do with opaque structs - checkfuncname = '_cffi_check_%s_%s' % (prefix, name) - layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) - cname = ('%s %s' % (prefix, name)).strip() + checkfuncname = f'_cffi_check_{prefix}_{name}' + layoutfuncname = f'_cffi_layout_{prefix}_{name}' + cname = (f'{prefix} {name}').strip() # prnt = self._prnt - prnt('static void %s(%s *p)' % (checkfuncname, cname)) + prnt(f'static void {checkfuncname}({cname} *p)') prnt('{') prnt(' /* only to generate compile-time warnings or errors */') prnt(' (void)p;') @@ -477,52 +473,51 @@ def _generate_struct_or_union_decl(self, tp, prefix, name): if (isinstance(ftype, model.PrimitiveType) and ftype.is_integer_type()) or fbitsize >= 0: # accept all integers, but complain on float or double - prnt(' (void)((p->%s) << 1);' % fname) + prnt(f' (void)((p->{fname}) << 1);') else: # only accept exactly the type declared. try: - prnt(' { %s = &p->%s; (void)tmp; }' % ( - ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual), + prnt(' {{ {} = &p->{}; (void)tmp; }}'.format( + ftype.get_c_name('*tmp', f'field {fname!r}', quals=fqual), fname)) except VerificationError as e: - prnt(' /* %s */' % str(e)) # cannot verify it, ignore + prnt(f' /* {str(e)} */') # cannot verify it, ignore prnt('}') prnt('static PyObject *') - prnt('%s(PyObject *self, PyObject *noarg)' % (layoutfuncname,)) + prnt(f'{layoutfuncname}(PyObject *self, PyObject *noarg)') prnt('{') - prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname) + prnt(f' struct _cffi_aligncheck {{ char x; {cname} y; }};') prnt(' static Py_ssize_t nums[] = {') - prnt(' sizeof(%s),' % cname) + prnt(f' sizeof({cname}),') prnt(' offsetof(struct _cffi_aligncheck, y),') for fname, ftype, fbitsize, fqual in tp.enumfields(): if fbitsize >= 0: continue # xxx ignore fbitsize for now - prnt(' offsetof(%s, %s),' % (cname, fname)) + prnt(f' offsetof({cname}, {fname}),') if isinstance(ftype, model.ArrayType) and ftype.length is None: - prnt(' 0, /* %s */' % ftype._get_c_name()) + prnt(f' 0, /* {ftype._get_c_name()} */') else: - prnt(' sizeof(((%s *)0)->%s),' % (cname, fname)) + prnt(f' sizeof((({cname} *)0)->{fname}),') prnt(' -1') prnt(' };') prnt(' (void)self; /* unused */') prnt(' (void)noarg; /* unused */') prnt(' return _cffi_get_struct_layout(nums);') prnt(' /* the next line is not executed, but compiled */') - prnt(' %s(0);' % (checkfuncname,)) + prnt(f' {checkfuncname}(0);') prnt('}') prnt() def _generate_struct_or_union_method(self, tp, prefix, name): if tp.fldnames is None: return # nothing to do with opaque structs - layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) - self._prnt(' {"%s", %s, METH_NOARGS, NULL},' % (layoutfuncname, - layoutfuncname)) + layoutfuncname = f'_cffi_layout_{prefix}_{name}' + self._prnt(f' {{"{layoutfuncname}", {layoutfuncname}, METH_NOARGS, NULL}},') def _loading_struct_or_union(self, tp, prefix, name, module): if tp.fldnames is None: return # nothing to do with opaque structs - layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) + layoutfuncname = f'_cffi_layout_{prefix}_{name}' # function = getattr(module, layoutfuncname) layout = function() @@ -537,7 +532,7 @@ def _loading_struct_or_union(self, tp, prefix, name, module): assert len(fieldofs) == len(fieldsize) == len(tp.fldnames) tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment else: - cname = ('%s %s' % (prefix, name)).strip() + cname = (f'{prefix} {name}').strip() self._struct_pending_verification[tp] = layout, cname def _loaded_struct_or_union(self, tp): @@ -562,11 +557,11 @@ def check(realvalue, expectedvalue, msg): if fbitsize >= 0: continue # xxx ignore fbitsize for now check(layout[i], ffi.offsetof(BStruct, fname), - "wrong offset for field %r" % (fname,)) + f"wrong offset for field {fname!r}") if layout[i+1] != 0: BField = ffi._get_cached_btype(ftype) check(layout[i+1], ffi.sizeof(BField), - "wrong size for field %r" % (fname,)) + f"wrong size for field {fname!r}") i += 2 assert i == len(layout) @@ -605,13 +600,13 @@ def _generate_cpy_const(self, is_int, name, tp=None, category='const', vartp=None, delayed=True, size_too=False, check_value=None): prnt = self._prnt - funcname = '_cffi_%s_%s' % (category, name) - prnt('static int %s(PyObject *lib)' % funcname) + funcname = f'_cffi_{category}_{name}' + prnt(f'static int {funcname}(PyObject *lib)') prnt('{') prnt(' PyObject *o;') prnt(' int res;') if not is_int: - prnt(' %s;' % (vartp or tp).get_c_name(' i', name)) + prnt(' {};'.format((vartp or tp).get_c_name(' i', name))) else: assert category == 'const' # @@ -623,28 +618,27 @@ def _generate_cpy_const(self, is_int, name, tp=None, category='const', realexpr = '&' + name else: realexpr = name - prnt(' i = (%s);' % (realexpr,)) - prnt(' o = %s;' % (self._convert_expr_from_c(tp, 'i', + prnt(f' i = ({realexpr});') + prnt(' o = {};'.format(self._convert_expr_from_c(tp, 'i', 'variable type'),)) assert delayed else: - prnt(' o = _cffi_from_c_int_const(%s);' % name) + prnt(f' o = _cffi_from_c_int_const({name});') prnt(' if (o == NULL)') prnt(' return -1;') if size_too: prnt(' {') prnt(' PyObject *o1 = o;') - prnt(' o = Py_BuildValue("On", o1, (Py_ssize_t)sizeof(%s));' - % (name,)) + prnt(f' o = Py_BuildValue("On", o1, (Py_ssize_t)sizeof({name}));') prnt(' Py_DECREF(o1);') prnt(' if (o == NULL)') prnt(' return -1;') prnt(' }') - prnt(' res = PyObject_SetAttrString(lib, "%s", o);' % name) + prnt(f' res = PyObject_SetAttrString(lib, "{name}", o);') prnt(' Py_DECREF(o);') prnt(' if (res < 0)') prnt(' return -1;') - prnt(' return %s;' % self._chained_list_constants[delayed]) + prnt(f' return {self._chained_list_constants[delayed]};') self._chained_list_constants[delayed] = funcname + '(lib)' prnt('}') prnt() @@ -674,11 +668,10 @@ def _check_int_constant_value(self, name, value, err_prefix=''): prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % ( name, name, value)) prnt(' char buf[64];') - prnt(' if ((%s) <= 0)' % name) - prnt(' snprintf(buf, 63, "%%ld", (long)(%s));' % name) + prnt(f' if (({name}) <= 0)') + prnt(f' snprintf(buf, 63, "%ld", (long)({name}));') prnt(' else') - prnt(' snprintf(buf, 63, "%%lu", (unsigned long)(%s));' % - name) + prnt(f' snprintf(buf, 63, "%lu", (unsigned long)({name}));') prnt(' PyErr_Format(_cffi_VerificationError,') prnt(' "%s%s has the real value %s, not %s",') prnt(' "%s", "%s", buf, "%d");' % ( @@ -689,7 +682,7 @@ def _check_int_constant_value(self, name, value, err_prefix=''): def _enum_funcname(self, prefix, name): # "$enum_$1" => "___D_enum____D_1" name = name.replace('$', '___D_') - return '_cffi_e_%s_%s' % (prefix, name) + return f'_cffi_e_{prefix}_{name}' def _generate_cpy_enum_decl(self, tp, name, prefix='enum'): if tp.partial: @@ -699,12 +692,12 @@ def _generate_cpy_enum_decl(self, tp, name, prefix='enum'): # funcname = self._enum_funcname(prefix, name) prnt = self._prnt - prnt('static int %s(PyObject *lib)' % funcname) + prnt(f'static int {funcname}(PyObject *lib)') prnt('{') for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): self._check_int_constant_value(enumerator, enumvalue, - "enum %s: " % name) - prnt(' return %s;' % self._chained_list_constants[True]) + f"enum {name}: ") + prnt(f' return {self._chained_list_constants[True]};') self._chained_list_constants[True] = funcname + '(lib)' prnt('}') prnt() @@ -771,8 +764,7 @@ def _loaded_cpy_variable(self, tp, name, module, library): length, rest = divmod(size, self.ffi.sizeof(BItemType)) if rest != 0: raise VerificationError( - "bad size: %r does not seem to be an array of %s" % - (name, tp.item)) + f"bad size: {name!r} does not seem to be an array of {tp.item}") tp = tp.resolve_length(length) # 'value' is a which we have to replace with # a if the N is actually known @@ -798,7 +790,7 @@ def _generate_setup_custom(self): prnt = self._prnt prnt('static int _cffi_setup_custom(PyObject *lib)') prnt('{') - prnt(' return %s;' % self._chained_list_constants[True]) + prnt(f' return {self._chained_list_constants[True]};') prnt('}') cffimod_header = r''' diff --git a/src/cffi/vengine_gen.py b/src/cffi/vengine_gen.py index 0209c794a..2f4d3d004 100644 --- a/src/cffi/vengine_gen.py +++ b/src/cffi/vengine_gen.py @@ -60,7 +60,7 @@ def write_source_to_f(self): else: prefix = 'init' modname = self.verifier.get_module_name() - prnt("void %s%s(void) { }\n" % (prefix, modname)) + prnt(f"void {prefix}{modname}(void) {{ }}\n") def load_library(self, flags=0): # import it with the CFFI backend @@ -100,11 +100,10 @@ def _generate(self, step_name): for name, tp in self._get_declarations(): kind, realname = name.split(' ', 1) try: - method = getattr(self, '_generate_gen_%s_%s' % (kind, - step_name)) + method = getattr(self, f'_generate_gen_{kind}_{step_name}') except AttributeError: raise VerificationError( - "not implemented in verify(): %r" % name) + f"not implemented in verify(): {name!r}") try: method(tp, realname) except Exception as e: @@ -114,7 +113,7 @@ def _generate(self, step_name): def _load(self, module, step_name, **kwds): for name, tp in self._get_declarations(): kind, realname = name.split(' ', 1) - method = getattr(self, '_%s_gen_%s' % (step_name, kind)) + method = getattr(self, f'_{step_name}_gen_{kind}') try: method(tp, realname, module, **kwds) except Exception as e: @@ -153,22 +152,22 @@ def _generate_gen_function_decl(self, tp, name): if isinstance(type, model.StructOrUnion): indirection = '*' argnames.append('%sx%d' % (indirection, i)) - context = 'argument of %s' % name - arglist = [type.get_c_name(' %s' % arg, context) + context = f'argument of {name}' + arglist = [type.get_c_name(f' {arg}', context) for type, arg in zip(tp.args, argnames)] tpresult = tp.result if isinstance(tpresult, model.StructOrUnion): arglist.insert(0, tpresult.get_c_name(' *r', context)) tpresult = model.void_type arglist = ', '.join(arglist) or 'void' - wrappername = '_cffi_f_%s' % name + wrappername = f'_cffi_f_{name}' self.export_symbols.append(wrappername) if tp.abi: abi = tp.abi + ' ' else: abi = '' - funcdecl = ' %s%s(%s)' % (abi, wrappername, arglist) - context = 'result of %s' % name + funcdecl = f' {abi}{wrappername}({arglist})' + context = f'result of {name}' prnt(tpresult.get_c_name(funcdecl, context)) prnt('{') # @@ -178,7 +177,7 @@ def _generate_gen_function_decl(self, tp, name): result_code = 'return ' else: result_code = '' - prnt(' %s%s(%s);' % (result_code, name, ', '.join(argnames))) + prnt(' {}{}({});'.format(result_code, name, ', '.join(argnames))) prnt('}') prnt() @@ -202,9 +201,8 @@ def _loaded_gen_function(self, tp, name, module, library): indirect_result = tp.result if isinstance(indirect_result, model.StructOrUnion): if indirect_result.fldtypes is None: - raise TypeError("'%s' is used as result type, " - "but is opaque" % ( - indirect_result._get_c_name(),)) + raise TypeError(f"'{indirect_result._get_c_name()}' is used as result type, " + "but is opaque") indirect_result = model.PointerType(indirect_result) indirect_args.insert(0, indirect_result) indirections.insert(0, ("result", indirect_result)) @@ -212,7 +210,7 @@ def _loaded_gen_function(self, tp, name, module, library): tp = model.FunctionPtrType(tuple(indirect_args), indirect_result, tp.ellipsis) BFunc = self.ffi._get_cached_btype(tp) - wrappername = '_cffi_f_%s' % name + wrappername = f'_cffi_f_{name}' newfunction = module.load_function(BFunc, wrappername) for i, typ in indirections: newfunction = self._make_struct_wrapper(newfunction, i, typ, @@ -262,12 +260,12 @@ def _loaded_gen_union(self, tp, name, module, **kwds): def _generate_struct_or_union_decl(self, tp, prefix, name): if tp.fldnames is None: return # nothing to do with opaque structs - checkfuncname = '_cffi_check_%s_%s' % (prefix, name) - layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) - cname = ('%s %s' % (prefix, name)).strip() + checkfuncname = f'_cffi_check_{prefix}_{name}' + layoutfuncname = f'_cffi_layout_{prefix}_{name}' + cname = (f'{prefix} {name}').strip() # prnt = self._prnt - prnt('static void %s(%s *p)' % (checkfuncname, cname)) + prnt(f'static void {checkfuncname}({cname} *p)') prnt('{') prnt(' /* only to generate compile-time warnings or errors */') prnt(' (void)p;') @@ -275,43 +273,43 @@ def _generate_struct_or_union_decl(self, tp, prefix, name): if (isinstance(ftype, model.PrimitiveType) and ftype.is_integer_type()) or fbitsize >= 0: # accept all integers, but complain on float or double - prnt(' (void)((p->%s) << 1);' % fname) + prnt(f' (void)((p->{fname}) << 1);') else: # only accept exactly the type declared. try: - prnt(' { %s = &p->%s; (void)tmp; }' % ( - ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual), + prnt(' {{ {} = &p->{}; (void)tmp; }}'.format( + ftype.get_c_name('*tmp', f'field {fname!r}', quals=fqual), fname)) except VerificationError as e: - prnt(' /* %s */' % str(e)) # cannot verify it, ignore + prnt(f' /* {str(e)} */') # cannot verify it, ignore prnt('}') self.export_symbols.append(layoutfuncname) - prnt('intptr_t %s(intptr_t i)' % (layoutfuncname,)) + prnt(f'intptr_t {layoutfuncname}(intptr_t i)') prnt('{') - prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname) + prnt(f' struct _cffi_aligncheck {{ char x; {cname} y; }};') prnt(' static intptr_t nums[] = {') - prnt(' sizeof(%s),' % cname) + prnt(f' sizeof({cname}),') prnt(' offsetof(struct _cffi_aligncheck, y),') for fname, ftype, fbitsize, fqual in tp.enumfields(): if fbitsize >= 0: continue # xxx ignore fbitsize for now - prnt(' offsetof(%s, %s),' % (cname, fname)) + prnt(f' offsetof({cname}, {fname}),') if isinstance(ftype, model.ArrayType) and ftype.length is None: - prnt(' 0, /* %s */' % ftype._get_c_name()) + prnt(f' 0, /* {ftype._get_c_name()} */') else: - prnt(' sizeof(((%s *)0)->%s),' % (cname, fname)) + prnt(f' sizeof((({cname} *)0)->{fname}),') prnt(' -1') prnt(' };') prnt(' return nums[i];') prnt(' /* the next line is not executed, but compiled */') - prnt(' %s(0);' % (checkfuncname,)) + prnt(f' {checkfuncname}(0);') prnt('}') prnt() def _loading_struct_or_union(self, tp, prefix, name, module): if tp.fldnames is None: return # nothing to do with opaque structs - layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) + layoutfuncname = f'_cffi_layout_{prefix}_{name}' # BFunc = self.ffi._typeof_locked("intptr_t(*)(intptr_t)")[0] function = module.load_function(BFunc, layoutfuncname) @@ -333,7 +331,7 @@ def _loading_struct_or_union(self, tp, prefix, name, module): assert len(fieldofs) == len(fieldsize) == len(tp.fldnames) tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment else: - cname = ('%s %s' % (prefix, name)).strip() + cname = (f'{prefix} {name}').strip() self._struct_pending_verification[tp] = layout, cname def _loaded_struct_or_union(self, tp): @@ -358,11 +356,11 @@ def check(realvalue, expectedvalue, msg): if fbitsize >= 0: continue # xxx ignore fbitsize for now check(layout[i], ffi.offsetof(BStruct, fname), - "wrong offset for field %r" % (fname,)) + f"wrong offset for field {fname!r}") if layout[i+1] != 0: BField = ffi._get_cached_btype(ftype) check(layout[i+1], ffi.sizeof(BField), - "wrong size for field %r" % (fname,)) + f"wrong size for field {fname!r}") i += 2 assert i == len(layout) @@ -394,22 +392,22 @@ def _loaded_gen_anonymous(self, tp, name, module, **kwds): def _generate_gen_const(self, is_int, name, tp=None, category='const', check_value=None): prnt = self._prnt - funcname = '_cffi_%s_%s' % (category, name) + funcname = f'_cffi_{category}_{name}' self.export_symbols.append(funcname) if check_value is not None: assert is_int assert category == 'const' - prnt('int %s(char *out_error)' % funcname) + prnt(f'int {funcname}(char *out_error)') prnt('{') self._check_int_constant_value(name, check_value) prnt(' return 0;') prnt('}') elif is_int: assert category == 'const' - prnt('int %s(long long *out_value)' % funcname) + prnt(f'int {funcname}(long long *out_value)') prnt('{') - prnt(' *out_value = (long long)(%s);' % (name,)) - prnt(' return (%s) <= 0;' % (name,)) + prnt(f' *out_value = (long long)({name});') + prnt(f' return ({name}) <= 0;') prnt('}') else: assert tp is not None @@ -422,9 +420,9 @@ def _generate_gen_const(self, is_int, name, tp=None, category='const', if category == 'const' and isinstance(tp, model.StructOrUnion): extra = 'const *' ampersand = '&' - prnt(tp.get_c_name(' %s%s(void)' % (extra, funcname), name)) + prnt(tp.get_c_name(f' {extra}{funcname}(void)', name)) prnt('{') - prnt(' return (%s%s);' % (ampersand, name)) + prnt(f' return ({ampersand}{name});') prnt('}') prnt() @@ -435,7 +433,7 @@ def _generate_gen_constant_decl(self, tp, name): _loading_gen_constant = _loaded_noop def _load_constant(self, is_int, tp, name, module, check_value=None): - funcname = '_cffi_const_%s' % name + funcname = f'_cffi_const_{name}' if check_value is not None: assert is_int self._load_known_int_constant(module, funcname) @@ -480,11 +478,10 @@ def _check_int_constant_value(self, name, value): prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % ( name, name, value)) prnt(' char buf[64];') - prnt(' if ((%s) <= 0)' % name) - prnt(' sprintf(buf, "%%ld", (long)(%s));' % name) + prnt(f' if (({name}) <= 0)') + prnt(f' sprintf(buf, "%ld", (long)({name}));') prnt(' else') - prnt(' sprintf(buf, "%%lu", (unsigned long)(%s));' % - name) + prnt(f' sprintf(buf, "%lu", (unsigned long)({name}));') prnt(' sprintf(out_error, "%s has the real value %s, not %s",') prnt(' "%s", buf, "%d");' % (name[:100], value)) prnt(' return -1;') @@ -504,7 +501,7 @@ def _load_known_int_constant(self, module, funcname): def _enum_funcname(self, prefix, name): # "$enum_$1" => "___D_enum____D_1" name = name.replace('$', '___D_') - return '_cffi_e_%s_%s' % (prefix, name) + return f'_cffi_e_{prefix}_{name}' def _generate_gen_enum_decl(self, tp, name, prefix='enum'): if tp.partial: @@ -515,7 +512,7 @@ def _generate_gen_enum_decl(self, tp, name, prefix='enum'): funcname = self._enum_funcname(prefix, name) self.export_symbols.append(funcname) prnt = self._prnt - prnt('int %s(char *out_error)' % funcname) + prnt(f'int {funcname}(char *out_error)') prnt('{') for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): self._check_int_constant_value(enumerator, enumvalue) @@ -567,11 +564,11 @@ def _generate_gen_variable_decl(self, tp, name): if isinstance(tp, model.ArrayType): if tp.length_is_unknown(): prnt = self._prnt - funcname = '_cffi_sizeof_%s' % (name,) + funcname = f'_cffi_sizeof_{name}' self.export_symbols.append(funcname) - prnt("size_t %s(void)" % funcname) + prnt(f"size_t {funcname}(void)") prnt("{") - prnt(" return sizeof(%s);" % (name,)) + prnt(f" return sizeof({name});") prnt("}") tp_ptr = model.PointerType(tp.item) self._generate_gen_const(False, name, tp_ptr) @@ -585,7 +582,7 @@ def _loaded_gen_variable(self, tp, name, module, library): if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the # sense that "a=..." is forbidden if tp.length_is_unknown(): - funcname = '_cffi_sizeof_%s' % (name,) + funcname = f'_cffi_sizeof_{name}' BFunc = self.ffi._typeof_locked('size_t(*)(void)')[0] function = module.load_function(BFunc, funcname) size = function() @@ -593,8 +590,7 @@ def _loaded_gen_variable(self, tp, name, module, library): length, rest = divmod(size, self.ffi.sizeof(BItemType)) if rest != 0: raise VerificationError( - "bad size: %r does not seem to be an array of %s" % - (name, tp.item)) + f"bad size: {name!r} does not seem to be an array of {tp.item}") tp = tp.resolve_length(length) tp_ptr = model.PointerType(tp.item) value = self._load_constant(False, tp_ptr, name, module) @@ -608,7 +604,7 @@ def _loaded_gen_variable(self, tp, name, module, library): return # remove ptr= from the library instance, and replace # it by a property on the class, which reads/writes into ptr[0]. - funcname = '_cffi_var_%s' % name + funcname = f'_cffi_var_{name}' BFunc = self.ffi._typeof_locked(tp.get_c_name('*(*)(void)', name))[0] function = module.load_function(BFunc, funcname) ptr = function() diff --git a/src/cffi/verifier.py b/src/cffi/verifier.py index 96baadb6f..e0f308412 100644 --- a/src/cffi/verifier.py +++ b/src/cffi/verifier.py @@ -35,7 +35,7 @@ def __init__(self, ffi, preamble, tmpdir=None, modulename=None, if ffi._parser._uses_new_feature: raise VerificationError( "feature not supported with ffi.verify(), but only " - "with ffi.set_source(): %s" % (ffi._parser._uses_new_feature,)) + f"with ffi.set_source(): {ffi._parser._uses_new_feature}") self.ffi = ffi self.preamble = preamble if not modulename: @@ -60,8 +60,7 @@ def __init__(self, ffi, preamble, tmpdir=None, modulename=None, k1 = k1.lstrip('0x').rstrip('L') k2 = hex(binascii.crc32(key[1::2]) & 0xffffffff) k2 = k2.lstrip('0').rstrip('L') - modulename = '_cffi_%s_%s%s%s' % (tag, self._vengine._class_key, - k1, k2) + modulename = f'_cffi_{tag}_{self._vengine._class_key}{k1}{k2}' suffix = _get_so_suffixes()[0] self.tmpdir = tmpdir or _caller_dir_pycache() self.sourcefilename = os.path.join(self.tmpdir, modulename + source_extension) @@ -136,8 +135,7 @@ def make_relative_to(self, kwds, relative_to): if key in kwds: lst = kwds[key] if not isinstance(lst, (list, tuple)): - raise TypeError("keyword '%s' should be a list or tuple" - % (key,)) + raise TypeError(f"keyword '{key}' should be a list or tuple") lst = [os.path.join(dirname, fn) for fn in lst] kwds[key] = lst return kwds diff --git a/testing/cffi0/backend_tests.py b/testing/cffi0/backend_tests.py index ce11044d7..73c636e82 100644 --- a/testing/cffi0/backend_tests.py +++ b/testing/cffi0/backend_tests.py @@ -73,7 +73,7 @@ def _test_int_type(self, ffi, c_decl, size, unsigned): assert q == p assert int(q) == int(p) assert hash(q) == hash(p) - c_decl_ptr = '%s *' % c_decl + c_decl_ptr = f'{c_decl} *' pytest.raises(OverflowError, ffi.new, c_decl_ptr, min - 1) pytest.raises(OverflowError, ffi.new, c_decl_ptr, max + 1) pytest.raises(OverflowError, ffi.new, c_decl_ptr, long(min - 1)) @@ -1094,7 +1094,7 @@ def test_anonymous_struct(self): def test_struct_with_two_usages(self): for name in ['foo_s', '']: # anonymous or not ffi = FFI(backend=self.Backend()) - ffi.cdef("typedef struct %s { int a; } foo_t, *foo_p;" % name) + ffi.cdef(f"typedef struct {name} {{ int a; }} foo_t, *foo_p;") f = ffi.new("foo_t *", [12345]) ps = ffi.new("foo_p[]", [f]) @@ -1888,7 +1888,7 @@ def test_struct_packed(self): assert ffi.alignof("struct is_packed8") == 4 for name in ['is_packed', 'is_packed1', 'is_packed2', 'is_packed4', 'is_packed8']: - s = ffi.new("struct %s[2]" % name) + s = ffi.new(f"struct {name}[2]") s[0].b = 42623381 s[0].a = b'X' s[1].b = -4892220 diff --git a/testing/cffi0/test_cdata.py b/testing/cffi0/test_cdata.py index 9601b812d..7bc66a1b6 100644 --- a/testing/cffi0/test_cdata.py +++ b/testing/cffi0/test_cdata.py @@ -17,9 +17,9 @@ def new_primitive_type(self, name): def new_void_type(self): return FakeType("void") def new_pointer_type(self, x): - return FakeType('ptr-to-%r' % (x,)) + return FakeType(f'ptr-to-{x!r}') def new_array_type(self, x, y): - return FakeType('array-from-%r-len-%r' % (x, y)) + return FakeType(f'array-from-{x!r}-len-{y!r}') def cast(self, x, y): return 'casted!' def _get_types(self): diff --git a/testing/cffi0/test_ffi_backend.py b/testing/cffi0/test_ffi_backend.py index ff75dba61..e150d13de 100644 --- a/testing/cffi0/test_ffi_backend.py +++ b/testing/cffi0/test_ffi_backend.py @@ -184,7 +184,7 @@ def check(self, source, expected_ofs_y, expected_align, expected_size): # The numbers expected from MSVC are not explicitly written # in this file, and will just be taken from the compiler. ffi = FFI() - ffi.cdef("struct s1 { %s };" % source) + ffi.cdef(f"struct s1 {{ {source} }};") ctype = ffi.typeof("struct s1") # verify the information with gcc ffi1 = FFI() @@ -198,19 +198,19 @@ def check(self, source, expected_ofs_y, expected_align, expected_size): for iname in enumerate(fnames)] lib = ffi1.verify(""" #include - struct s1 { %s }; - struct sa { char a; struct s1 b; }; + struct s1 {{ {} }}; + struct sa {{ char a; struct s1 b; }}; #define Gofs_y offsetof(struct s1, y) #define Galign offsetof(struct sa, b) #define Gsize sizeof(struct s1) struct s1 *try_with_value(int fieldnum, long long value) - { + {{ static struct s1 s; memset(&s, 0, sizeof(s)); - switch (fieldnum) { %s } + switch (fieldnum) {{ {} }} return &s; - } - """ % (source, ' '.join(setters))) + }} + """.format(source, ' '.join(setters))) if sys.platform == 'win32': expected_ofs_y = lib.Gofs_y expected_align = lib.Galign diff --git a/testing/cffi0/test_function.py b/testing/cffi0/test_function.py index 3cdd8f6a5..847c15481 100644 --- a/testing/cffi0/test_function.py +++ b/testing/cffi0/test_function.py @@ -67,7 +67,7 @@ def test_getenv_no_return_value(self): def test_dlopen_filename(self): path = ctypes.util.find_library(lib_m) if not path: - pytest.skip("%s not found" % lib_m) + pytest.skip(f"{lib_m} not found") ffi = FFI(backend=self.Backend()) ffi.cdef(""" double cos(double x); @@ -216,7 +216,7 @@ def cb(charp): return 42 fptr = ffi.callback("int(*)(const char *txt)", cb) assert fptr != ffi.callback("int(*)(const char *)", cb) - assert repr(fptr) == "" % (cb,) + assert repr(fptr) == f"" res = fptr(b"Hello") assert res == 42 # diff --git a/testing/cffi0/test_ownlib.py b/testing/cffi0/test_ownlib.py index d1856819c..852ac7d92 100644 --- a/testing/cffi0/test_ownlib.py +++ b/testing/cffi0/test_ownlib.py @@ -144,7 +144,7 @@ def setup_class(cls): # no mingw from distutils.msvc9compiler import get_build_version version = get_build_version() - toolskey = "VS%0.f0COMNTOOLS" % version + toolskey = f"VS{version:0.0f}0COMNTOOLS" toolsdir = os.environ.get(toolskey, None) if toolsdir is None: return @@ -174,7 +174,7 @@ def setup_class(cls): unicode_name = u+'testownlib' encoded = str(unicode_name) subprocess.check_call( - "cc testownlib.c -shared -fPIC -o '%s.so'" % (encoded,), + f"cc testownlib.c -shared -fPIC -o '{encoded}.so'", cwd=str(udir), shell=True) cls.module = f"{udir / unicode_name}.so" print(repr(cls.module)) diff --git a/testing/cffi0/test_parsing.py b/testing/cffi0/test_parsing.py index 3e47bcdd8..e9dd0987d 100644 --- a/testing/cffi0/test_parsing.py +++ b/testing/cffi0/test_parsing.py @@ -24,14 +24,14 @@ def new_function_type(self, args, result, has_varargs): args = [arg.cdecl for arg in args] result = result.cdecl return FakeType( - '' % (', '.join(args), result, has_varargs)) + ''.format(', '.join(args), result, has_varargs)) def new_primitive_type(self, name): assert name == name.lower() - return FakeType('<%s>' % name) + return FakeType(f'<{name}>') def new_pointer_type(self, itemtype): - return FakeType('' % (itemtype,)) + return FakeType(f'') def new_struct_type(self, name): return FakeStruct(name) @@ -42,7 +42,7 @@ def complete_struct_or_union(self, s, fields, tp=None, s.fields = fields def new_array_type(self, ptrtype, length): - return FakeType('' % (ptrtype, length)) + return FakeType(f'') def new_void_type(self): return FakeType("") @@ -371,9 +371,9 @@ def test_redefine_common_type(): prefix = "" if sys.version_info < (3,) else "b" ffi = FFI() ffi.cdef("typedef char FILE;") - assert repr(ffi.cast("FILE", 123)) == "" % prefix + assert repr(ffi.cast("FILE", 123)) == f"" ffi.cdef("typedef char int32_t;") - assert repr(ffi.cast("int32_t", 123)) == "" % prefix + assert repr(ffi.cast("int32_t", 123)) == f"" ffi = FFI() ffi.cdef("typedef int bool, *FILE;") assert repr(ffi.cast("bool", 123)) == "" @@ -539,9 +539,9 @@ def test_stdcall(): else: stdcall = '' assert str(tp) == ( - "" % (stdcall, stdcall)) + f"short({stdcall}*)(short))'>") def test_extern_python(): ffi = FFI() @@ -612,7 +612,7 @@ def test_unsigned_int_suffix_for_constant(): C = ffi.dlopen(None) for base, expected_result in (('bin', 2), ('oct', 8), ('dec', 10), ('hex', 16)): for index in range(7): - assert getattr(C, '{base}_{index}'.format(base=base, index=index)) == expected_result + assert getattr(C, f'{base}_{index}') == expected_result def test_missing_newline_bug(): ffi = FFI(backend=FakeBackend()) diff --git a/testing/cffi0/test_verify.py b/testing/cffi0/test_verify.py index dfc8337ea..278b789d0 100644 --- a/testing/cffi0/test_verify.py +++ b/testing/cffi0/test_verify.py @@ -156,7 +156,7 @@ def test_strlen_approximate(): def test_return_approximate(): for typename in ['short', 'int', 'long', 'long long']: ffi = FFI() - ffi.cdef("%s foo(signed char x);" % typename) + ffi.cdef(f"{typename} foo(signed char x);") lib = ffi.verify("signed char foo(signed char x) { return x;}") assert lib.foo(-128) == -128 assert lib.foo(+127) == +127 @@ -256,13 +256,12 @@ def test_all_integer_and_float_types(): typenames.append(typename) # ffi = FFI() - ffi.cdef('\n'.join(["%s foo_%s(%s);" % (tp, tp.replace(' ', '_'), tp) + ffi.cdef('\n'.join(["{} foo_{}({});".format(tp, tp.replace(' ', '_'), tp) for tp in typenames])) - lib = ffi.verify('\n'.join(["%s foo_%s(%s x) { return (%s)(x+1); }" % - (tp, tp.replace(' ', '_'), tp, tp) + lib = ffi.verify('\n'.join(["{} foo_{}({} x) {{ return ({})(x+1); }}".format(tp, tp.replace(' ', '_'), tp, tp) for tp in typenames])) for typename in typenames: - foo = getattr(lib, 'foo_%s' % typename.replace(' ', '_')) + foo = getattr(lib, 'foo_{}'.format(typename.replace(' ', '_'))) assert foo(42) == 43 if sys.version < '3': assert foo(long(44)) == 45 @@ -290,22 +289,21 @@ def test_all_complex_types(): header = '' # ffi = FFI() - ffi.cdef('\n'.join(["%s foo_%s(%s);" % (tp, tp.replace(' ', '_'), tp) + ffi.cdef('\n'.join(["{} foo_{}({});".format(tp, tp.replace(' ', '_'), tp) for tp in typenames])) e = pytest.raises(VerificationError, ffi.verify, - header + '\n'.join(["%s foo_%s(%s x) { return x; }" % - (tp, tp.replace(' ', '_'), tp) + header + '\n'.join(["{} foo_{}({} x) {{ return x; }}".format(tp, tp.replace(' ', '_'), tp) for tp in typenames])) def test_var_signed_integer_types(): ffi = FFI() lst = all_signed_integer_types(ffi) - csource = "\n".join(["static %s somevar_%s;" % (tp, tp.replace(' ', '_')) + csource = "\n".join(["static {} somevar_{};".format(tp, tp.replace(' ', '_')) for tp in lst]) ffi.cdef(csource) lib = ffi.verify(csource) for tp in lst: - varname = 'somevar_%s' % tp.replace(' ', '_') + varname = 'somevar_{}'.format(tp.replace(' ', '_')) sz = ffi.sizeof(tp) max = (1 << (8*sz-1)) - 1 min = -(1 << (8*sz-1)) @@ -319,12 +317,12 @@ def test_var_signed_integer_types(): def test_var_unsigned_integer_types(): ffi = FFI() lst = all_unsigned_integer_types(ffi) - csource = "\n".join(["static %s somevar_%s;" % (tp, tp.replace(' ', '_')) + csource = "\n".join(["static {} somevar_{};".format(tp, tp.replace(' ', '_')) for tp in lst]) ffi.cdef(csource) lib = ffi.verify(csource) for tp in lst: - varname = 'somevar_%s' % tp.replace(' ', '_') + varname = 'somevar_{}'.format(tp.replace(' ', '_')) sz = ffi.sizeof(tp) if tp != '_Bool': max = (1 << (8*sz)) - 1 @@ -340,14 +338,13 @@ def test_var_unsigned_integer_types(): def test_fn_signed_integer_types(): ffi = FFI() lst = all_signed_integer_types(ffi) - cdefsrc = "\n".join(["%s somefn_%s(%s);" % (tp, tp.replace(' ', '_'), tp) + cdefsrc = "\n".join(["{} somefn_{}({});".format(tp, tp.replace(' ', '_'), tp) for tp in lst]) ffi.cdef(cdefsrc) - verifysrc = "\n".join(["%s somefn_%s(%s x) { return x; }" % - (tp, tp.replace(' ', '_'), tp) for tp in lst]) + verifysrc = "\n".join(["{} somefn_{}({} x) {{ return x; }}".format(tp, tp.replace(' ', '_'), tp) for tp in lst]) lib = ffi.verify(verifysrc) for tp in lst: - fnname = 'somefn_%s' % tp.replace(' ', '_') + fnname = 'somefn_{}'.format(tp.replace(' ', '_')) sz = ffi.sizeof(tp) max = (1 << (8*sz-1)) - 1 min = -(1 << (8*sz-1)) @@ -360,14 +357,13 @@ def test_fn_signed_integer_types(): def test_fn_unsigned_integer_types(): ffi = FFI() lst = all_unsigned_integer_types(ffi) - cdefsrc = "\n".join(["%s somefn_%s(%s);" % (tp, tp.replace(' ', '_'), tp) + cdefsrc = "\n".join(["{} somefn_{}({});".format(tp, tp.replace(' ', '_'), tp) for tp in lst]) ffi.cdef(cdefsrc) - verifysrc = "\n".join(["%s somefn_%s(%s x) { return x; }" % - (tp, tp.replace(' ', '_'), tp) for tp in lst]) + verifysrc = "\n".join(["{} somefn_{}({} x) {{ return x; }}".format(tp, tp.replace(' ', '_'), tp) for tp in lst]) lib = ffi.verify(verifysrc) for tp in lst: - fnname = 'somefn_%s' % tp.replace(' ', '_') + fnname = 'somefn_{}'.format(tp.replace(' ', '_')) sz = ffi.sizeof(tp) if tp != '_Bool': max = (1 << (8*sz)) - 1 @@ -445,12 +441,12 @@ def test_verify_typedefs(): for cdefed in types: for real in types: ffi = FFI() - ffi.cdef("typedef %s foo_t;" % cdefed) + ffi.cdef(f"typedef {cdefed} foo_t;") if cdefed == real: - ffi.verify("typedef %s foo_t;" % real) + ffi.verify(f"typedef {real} foo_t;") else: pytest.raises(VerificationError, ffi.verify, - "typedef %s foo_t;" % real) + f"typedef {real} foo_t;") def test_nondecl_struct(): ffi = FFI() @@ -527,21 +523,21 @@ def _check_field_match(typename, real, expect_mismatch): testing_by_size = (expect_mismatch == 'by_size') if testing_by_size: expect_mismatch = ffi.sizeof(typename) != ffi.sizeof(real) - ffi.cdef("struct foo_s { %s x; ...; };" % typename) + ffi.cdef(f"struct foo_s {{ {typename} x; ...; }};") try: - ffi.verify("struct foo_s { %s x; };" % real) + ffi.verify(f"struct foo_s {{ {real} x; }};") except VerificationError: if not expect_mismatch: if testing_by_size and typename != real: - print("ignoring mismatch between %s* and %s* even though " - "they have the same size" % (typename, real)) + print(f"ignoring mismatch between {typename}* and {real}* even though " + "they have the same size") return - raise AssertionError("unexpected mismatch: %s should be accepted " - "as equal to %s" % (typename, real)) + raise AssertionError(f"unexpected mismatch: {typename} should be accepted " + f"as equal to {real}") else: if expect_mismatch: raise AssertionError("mismatch not detected: " - "%s != %s" % (typename, real)) + f"{typename} != {real}") def test_struct_bad_sized_integer(): for typename in ['int8_t', 'int16_t', 'int32_t', 'int64_t']: @@ -715,7 +711,7 @@ def test_global_const_int_size(): else: raise AssertionError(value) ffi.cdef("static const unsigned short AA;") - lib = ffi.verify("#define AA %s\n" % vstr) + lib = ffi.verify(f"#define AA {vstr}\n") assert lib.AA == value assert type(lib.AA) is type(int(lib.AA)) @@ -862,7 +858,7 @@ def test_access_address_of_variable(): def test_access_array_variable(length=5): ffi = FFI() ffi.cdef("int foo(int);\n" - "static int somenumber[%s];" % (length,)) + f"static int somenumber[{length}];") lib = ffi.verify(""" static int somenumber[] = {2, 2, 3, 4, 5}; static int foo(int i) { @@ -877,7 +873,7 @@ def test_access_array_variable(length=5): assert repr(lib.somenumber).startswith("\n' v = Verifier(ffi, csrc, force_generic_engine=self.generic, libraries=[self.lib_m]) v.write_source() @@ -51,7 +51,7 @@ def test_write_source(self): def test_write_source_explicit_filename(self): ffi = FFI() ffi.cdef("double sin(double x);") - csrc = '/*hi there %s!*/\n#include \n' % self + csrc = f'/*hi there {self}!*/\n#include \n' v = Verifier(ffi, csrc, force_generic_engine=self.generic, libraries=[self.lib_m]) source_file = udir / 'write_source.c' @@ -63,7 +63,7 @@ def test_write_source_explicit_filename(self): def test_write_source_to_file_obj(self): ffi = FFI() ffi.cdef("double sin(double x);") - csrc = '/*hi there %s!*/\n#include \n' % self + csrc = f'/*hi there {self}!*/\n#include \n' v = Verifier(ffi, csrc, force_generic_engine=self.generic, libraries=[self.lib_m]) try: @@ -77,7 +77,7 @@ def test_write_source_to_file_obj(self): def test_compile_module(self): ffi = FFI() ffi.cdef("double sin(double x);") - csrc = '/*hi there %s!*/\n#include \n' % self + csrc = f'/*hi there {self}!*/\n#include \n' v = Verifier(ffi, csrc, force_generic_engine=self.generic, libraries=[self.lib_m]) v.compile_module() @@ -89,7 +89,7 @@ def test_compile_module(self): def test_compile_module_explicit_filename(self): ffi = FFI() ffi.cdef("double sin(double x);") - csrc = '/*hi there %s!2*/\n#include \n' % self + csrc = f'/*hi there {self}!2*/\n#include \n' v = Verifier(ffi, csrc, force_generic_engine=self.generic, libraries=[self.lib_m]) basename = self.__class__.__name__[:10] + '_test_compile_module' @@ -106,7 +106,7 @@ def test_name_from_checksum_of_cdef(self): names = [] for csrc in ['double', 'double', 'float']: ffi = FFI() - ffi.cdef("%s sin(double x);" % csrc) + ffi.cdef(f"{csrc} sin(double x);") v = Verifier(ffi, "#include ", force_generic_engine=self.generic, libraries=[self.lib_m]) @@ -125,7 +125,7 @@ def test_name_from_checksum_of_csrc(self): def test_load_library(self): ffi = FFI() ffi.cdef("double sin(double x);") - csrc = '/*hi there %s!3*/\n#include \n' % self + csrc = f'/*hi there {self}!3*/\n#include \n' v = Verifier(ffi, csrc, force_generic_engine=self.generic, libraries=[self.lib_m]) library = v.load_library() @@ -134,7 +134,7 @@ def test_load_library(self): def test_verifier_args(self): ffi = FFI() ffi.cdef("double sin(double x);") - csrc = '/*hi there %s!4*/#include "test_verifier_args.h"\n' % self + csrc = f'/*hi there {self}!4*/#include "test_verifier_args.h"\n' (udir / 'test_verifier_args.h').write_text('#include \n') v = Verifier(ffi, csrc, include_dirs=[str(udir)], force_generic_engine=self.generic, @@ -145,7 +145,7 @@ def test_verifier_args(self): def test_verifier_object_from_ffi(self): ffi = FFI() ffi.cdef("double sin(double x);") - csrc = "/*6%s*/\n#include " % self + csrc = f"/*6{self}*/\n#include " lib = ffi.verify(csrc, force_generic_engine=self.generic, libraries=[self.lib_m]) assert lib.sin(12.3) == math.sin(12.3) @@ -157,7 +157,7 @@ def test_verifier_object_from_ffi(self): def test_extension_object(self): ffi = FFI() ffi.cdef("double sin(double x);") - csrc = '/*7%s*/' % self + ''' + csrc = f'/*7{self}*/' + ''' #include #ifndef TEST_EXTENSION_OBJECT # error "define_macros missing" @@ -178,7 +178,7 @@ def test_extension_object(self): def test_extension_forces_write_source(self): ffi = FFI() ffi.cdef("double sin(double x);") - csrc = '/*hi there9!%s*/\n#include \n' % self + csrc = f'/*hi there9!{self}*/\n#include \n' v = Verifier(ffi, csrc, force_generic_engine=self.generic, libraries=[self.lib_m]) assert not os.path.exists(v.sourcefilename) @@ -191,7 +191,7 @@ def test_extension_object_extra_sources(self): extra_source = udir / 'extension_extra_sources.c' extra_source.write_text( 'double test1eoes(double x) { return x * 6.0; }\n') - csrc = '/*9%s*/' % self + ''' + csrc = f'/*9{self}*/' + ''' double test1eoes(double x); /* or #include "extra_sources.h" */ ''' lib = ffi.verify(csrc, sources=[str(extra_source)], @@ -217,7 +217,7 @@ def test_install_and_reload_module(self, targetpackage='', ext_package=''): def make_ffi(**verifier_args): ffi = FFI() - ffi.cdef("/* %s, %s, %s */" % (KEY, targetpackage, ext_package)) + ffi.cdef(f"/* {KEY}, {targetpackage}, {ext_package} */") ffi.cdef("double test1iarm(double x);") csrc = "double test1iarm(double x) { return x * 42.0; }" lib = ffi.verify(csrc, force_generic_engine=self.generic, @@ -264,7 +264,7 @@ def test_install_and_reload_module_ext_package_not_found(self): def test_tag(self): ffi = FFI() - ffi.cdef("/* %s test_tag */ double test1tag(double x);" % self) + ffi.cdef(f"/* {self} test_tag */ double test1tag(double x);") csrc = "double test1tag(double x) { return x - 42.0; }" lib = ffi.verify(csrc, force_generic_engine=self.generic, tag='xxtest_tagxx') @@ -273,7 +273,7 @@ def test_tag(self): def test_modulename(self): ffi = FFI() - ffi.cdef("/* %s test_modulename */ double test1foo(double x);" % self) + ffi.cdef(f"/* {self} test_modulename */ double test1foo(double x);") csrc = "double test1foo(double x) { return x - 63.0; }" modname = 'xxtest_modulenamexx%d' % (self.generic,) lib = ffi.verify(csrc, force_generic_engine=self.generic, diff --git a/testing/cffi1/test_cffi_binary.py b/testing/cffi1/test_cffi_binary.py index 84668bb12..f4f4e188e 100644 --- a/testing/cffi1/test_cffi_binary.py +++ b/testing/cffi1/test_cffi_binary.py @@ -8,7 +8,7 @@ def test_no_unknown_exported_symbols(): pytest.skip("_cffi_backend module is built-in") if not sys.platform.startswith('linux') or is_musl: pytest.skip("linux-only") - g = os.popen("objdump -T '%s'" % _cffi_backend.__file__, 'r') + g = os.popen(f"objdump -T '{_cffi_backend.__file__}'", 'r') for line in g: if not line.startswith('0'): continue @@ -23,5 +23,5 @@ def test_no_unknown_exported_symbols(): if name.startswith('ffi_') and 'Base' in line: continue if name not in ('init_cffi_backend', 'PyInit__cffi_backend', 'cffistatic_ffi_call'): - raise Exception("Unexpected exported name %r" % (name,)) + raise Exception(f"Unexpected exported name {name!r}") g.close() diff --git a/testing/cffi1/test_ffi_obj.py b/testing/cffi1/test_ffi_obj.py index b822636f5..0e4223a02 100644 --- a/testing/cffi1/test_ffi_obj.py +++ b/testing/cffi1/test_ffi_obj.py @@ -79,8 +79,7 @@ def test_ffi_docstrings(): if not methname.startswith('_'): method = getattr(_cffi1_backend.FFI, methname) if isinstance(method, check_type): - assert method.__doc__, "method FFI.%s() has no docstring" % ( - methname,) + assert method.__doc__, f"method FFI.{methname}() has no docstring" def test_ffi_NULL(): NULL = _cffi1_backend.FFI.NULL @@ -229,8 +228,8 @@ def test_ffi_invalid_type(): e = pytest.raises(ffi.error, ffi.cast, "\t\n\x01\x1f~\x7f\x80\xff", 0) marks = "?" if sys.version_info < (3,) else "??" assert str(e.value) == ("identifier expected\n" - " ??~?%s%s\n" - " ^" % (marks, marks)) + f" ??~?{marks}{marks}\n" + " ^") e = pytest.raises(ffi.error, ffi.cast, "X" * 600, 0) assert str(e.value) == ("undefined type name") @@ -446,7 +445,7 @@ def test_cast_from_int_type_to_bool(): ffi = _cffi1_backend.FFI() for basetype in ['char', 'short', 'int', 'long', 'long long']: for sign in ['signed', 'unsigned']: - type = '%s %s' % (sign, basetype) + type = f'{sign} {basetype}' assert int(ffi.cast("_Bool", ffi.cast(type, 42))) == 1 assert int(ffi.cast("bool", ffi.cast(type, 42))) == 1 assert int(ffi.cast("_Bool", ffi.cast(type, 0))) == 0 diff --git a/testing/cffi1/test_function_args.py b/testing/cffi1/test_function_args.py index daf3e644a..501974b2e 100644 --- a/testing/cffi1/test_function_args.py +++ b/testing/cffi1/test_function_args.py @@ -65,7 +65,7 @@ def build_type(tp): for (j, ftp) in enumerate(field_types)] fields = '\n '.join(fields) name = 's%d' % len(cdefs) - cdefs.append("typedef struct {\n %s\n} %s;" % (fields, name)) + cdefs.append(f"typedef struct {{\n {fields}\n}} {name};") structs[name] = field_types return name else: @@ -75,17 +75,17 @@ def build_type(tp): result = build_type(tp_result) TEST_RUN_COUNTER += 1 - signature = "%s testfargs(%s)" % (result, + signature = "{} testfargs({})".format(result, ', '.join(['%s a%d' % (arg, i) for (i, arg) in enumerate(args)]) or 'void') source = list(cdefs) - cdefs.append("%s;" % signature) - cdefs.append("extern %s testfargs_result;" % result) + cdefs.append(f"{signature};") + cdefs.append(f"extern {result} testfargs_result;") for i, arg in enumerate(args): cdefs.append("extern %s testfargs_arg%d;" % (arg, i)) - source.append("%s testfargs_result;" % result) + source.append(f"{result} testfargs_result;") for i, arg in enumerate(args): source.append("%s testfargs_arg%d;" % (arg, i)) source.append(signature) @@ -95,17 +95,16 @@ def build_type(tp): source.append(" return testfargs_result;") source.append("}") - typedef_line = "typedef %s;" % (signature.replace('testfargs', + typedef_line = "typedef {};".format(signature.replace('testfargs', '(*mycallback_t)'),) assert signature.endswith(')') - sig_callback = "%s testfcallback(mycallback_t callback)" % result + sig_callback = f"{result} testfcallback(mycallback_t callback)" cdefs.append(typedef_line) - cdefs.append("%s;" % sig_callback) + cdefs.append(f"{sig_callback};") source.append(typedef_line) source.append(sig_callback) source.append("{") - source.append(" return callback(%s);" % - ', '.join(["testfargs_arg%d" % i for i in range(len(args))])) + source.append(" return callback({});".format(', '.join(["testfargs_arg%d" % i for i in range(len(args))]))) source.append("}") ffi = FFI() @@ -118,14 +117,14 @@ def build_type(tp): from testing.udir import udir import subprocess with (udir / 'run1.py').open('w') as f: - f.write('import sys; sys.path = %r\n' % (sys.path,)) + f.write(f'import sys; sys.path = {sys.path!r}\n') f.write('from _CFFI_test_function_args_%d import ffi, lib\n' % TEST_RUN_COUNTER) for i in range(len(args)): f.write('a%d = ffi.new("%s *")\n' % (i, args[i])) aliststr = ', '.join(['a%d[0]' % i for i in range(len(args))]) - f.write('lib.testfargs(%s)\n' % aliststr) - f.write('ffi.addressof(lib, "testfargs")(%s)\n' % aliststr) + f.write(f'lib.testfargs({aliststr})\n') + f.write(f'ffi.addressof(lib, "testfargs")({aliststr})\n') print("checking for segfault for direct call...") rc = subprocess.call([sys.executable, 'run1.py'], cwd=str(udir)) assert rc == 0, rc @@ -184,13 +183,11 @@ def expand(value): from testing.udir import udir import subprocess with (udir / 'run1.py').open('w') as f: - f.write('import sys; sys.path = %r\n' % (sys.path,)) + f.write(f'import sys; sys.path = {sys.path!r}\n') f.write('from _CFFI_test_function_args_%d import ffi, lib\n' % TEST_RUN_COUNTER) - f.write('def callback(*args): return ffi.new("%s *")[0]\n' - % result) - f.write('fptr = ffi.callback("%s(%s)", callback)\n' - % (result, ','.join(args))) + f.write(f'def callback(*args): return ffi.new("{result} *")[0]\n') + f.write('fptr = ffi.callback("{}({})", callback)\n'.format(result, ','.join(args))) f.write('print(lib.testfcallback(fptr))\n') print("checking for segfault for callback...") rc = subprocess.call([sys.executable, 'run1.py'], cwd=str(udir)) @@ -201,7 +198,7 @@ def callback(*args): seen_args.append([expand(arg) for arg in args]) return returned_value - fptr = ffi.callback("%s(%s)" % (result, ','.join(args)), callback) + fptr = ffi.callback("{}({})".format(result, ','.join(args)), callback) print("CALL with callback") received_return = lib.testfcallback(fptr) diff --git a/testing/cffi1/test_new_ffi_1.py b/testing/cffi1/test_new_ffi_1.py index fe19c75c2..baa25b6bd 100644 --- a/testing/cffi1/test_new_ffi_1.py +++ b/testing/cffi1/test_new_ffi_1.py @@ -151,7 +151,7 @@ def _test_int_type(self, ffi, c_decl, size, unsigned): assert q == p assert int(q) == int(p) assert hash(q) == hash(p) - c_decl_ptr = '%s *' % c_decl + c_decl_ptr = f'{c_decl} *' pytest.raises(OverflowError, ffi.new, c_decl_ptr, min - 1) pytest.raises(OverflowError, ffi.new, c_decl_ptr, max + 1) pytest.raises(OverflowError, ffi.new, c_decl_ptr, long(min - 1)) @@ -745,7 +745,7 @@ def cb(n): def test_functionptr_advanced(self): t = ffi.typeof("int(*(*)(int))(int)") - assert repr(t) == "" % "int(*(*)(int))(int)" + assert repr(t) == "".format("int(*(*)(int))(int)") def test_functionptr_voidptr_return(self): def cb(): diff --git a/testing/cffi1/test_parse_c_type.py b/testing/cffi1/test_parse_c_type.py index 49a31d541..6d9efbd33 100644 --- a/testing/cffi1/test_parse_c_type.py +++ b/testing/cffi1/test_parse_c_type.py @@ -264,8 +264,8 @@ def test_fix_arg_types(): def test_enum(): for i in range(len(enum_names)): - assert parse("enum %s" % (enum_names[i],)) == ['->', Enum(i)] - assert parse("enum %s*" % (enum_names[i],)) == [Enum(i), + assert parse(f"enum {enum_names[i]}") == ['->', Enum(i)] + assert parse(f"enum {enum_names[i]}*") == [Enum(i), '->', Pointer(0)] def test_error(): @@ -316,20 +316,20 @@ def test_struct(): tag = "union" else: tag = "struct" - assert parse("%s %s" % (tag, struct_names[i])) == ['->', Struct(i)] - assert parse("%s %s*" % (tag, struct_names[i])) == [Struct(i), + assert parse(f"{tag} {struct_names[i]}") == ['->', Struct(i)] + assert parse(f"{tag} {struct_names[i]}*") == [Struct(i), '->', Pointer(0)] def test_exchanging_struct_union(): - parse_error("union %s" % (struct_names[0],), + parse_error(f"union {struct_names[0]}", "wrong kind of tag: struct vs union", 6) - parse_error("struct %s" % (struct_names[3],), + parse_error(f"struct {struct_names[3]}", "wrong kind of tag: struct vs union", 7) def test_identifier(): for i in range(len(identifier_names)): - assert parse("%s" % (identifier_names[i])) == ['->', Typename(i)] - assert parse("%s*" % (identifier_names[i])) == [Typename(i), + assert parse(f"{identifier_names[i]}") == ['->', Typename(i)] + assert parse(f"{identifier_names[i]}*") == [Typename(i), '->', Pointer(0)] def test_cffi_opcode_sync(): diff --git a/testing/cffi1/test_re_python.py b/testing/cffi1/test_re_python.py index fbca325e2..c1ac08d8e 100644 --- a/testing/cffi1/test_re_python.py +++ b/testing/cffi1/test_re_python.py @@ -138,7 +138,7 @@ def test_dlclose(): str_extmod = extmod e = pytest.raises(ffi.error, getattr, lib, 'add42') assert str(e.value) == ( - "library '%s' has been closed" % (str_extmod,)) + f"library '{str_extmod}' has been closed") ffi.dlclose(lib) # does not raise @pytest.mark.thread_unsafe( diff --git a/testing/cffi1/test_recompiler.py b/testing/cffi1/test_recompiler.py index 0245b8db3..06e615c00 100644 --- a/testing/cffi1/test_recompiler.py +++ b/testing/cffi1/test_recompiler.py @@ -36,7 +36,7 @@ def verify(ffi, module_name, source, *args, **kwds): ffi.set_source(module_name, source) if not os.environ.get('NO_CPP') and not no_cpp: # test the .cpp mode too kwds.setdefault('source_extension', '.cpp') - source = 'extern "C" {\n%s\n}' % (source,) + source = f'extern "C" {{\n{source}\n}}' elif sys.platform != 'win32' and not ignore_warnings: # add '-Werror' to the existing 'extra_compile_args' flags from testing.support import extra_compile_args @@ -246,7 +246,7 @@ def test_macro_check_value(): c_got = int(vals[j].replace('U', '').replace('L', ''), 0) c_compiler_msg = str(c_got) if c_got > 0: - c_compiler_msg += ' (0x%x)' % (c_got,) + c_compiler_msg += f' (0x{c_got:x})' # for i in range(len(vals)): attrname = 'FOO_%d_%d' % (i, j) @@ -256,8 +256,8 @@ def test_macro_check_value(): else: e = pytest.raises(ffi.error, getattr, lib, attrname) assert str(e.value) == ( - "the C compiler says '%s' is equal to " - "%s, but the cdef disagrees" % (attrname, c_compiler_msg)) + f"the C compiler says '{attrname}' is equal to " + f"{c_compiler_msg}, but the cdef disagrees") def test_constant(): ffi = FFI() @@ -1585,7 +1585,7 @@ def test_extern_python_1(): void boz(void); } """) - assert len(log) == 0, "got a warning: %r" % (log,) + assert len(log) == 0, f"got a warning: {log!r}" lib = verify(ffi, 'test_extern_python_1', """ static void baz(int, int); /* forward */ """) @@ -1671,7 +1671,7 @@ def bar(n): res = lib.bar(321) assert res is None msg = f.getvalue() - assert "rom cffi callback %r" % (bar,) in msg + assert f"rom cffi callback {bar!r}" in msg assert "rying to convert the result back to C:\n" in msg assert msg.endswith( "TypeError: callback with the return type 'void' must return None\n") @@ -2581,9 +2581,9 @@ def test_large_enum(): ffi = FFI() biglist = ['nn%d' % i for i in range(6000)] ffi.cdef( - """enum foo_s { %s };""" % ','.join(biglist)) + """enum foo_s {{ {} }};""".format(','.join(biglist))) lib = verify(ffi, "test_large_enum", """ - enum foo_s { %s };""" % ','.join(biglist)) + enum foo_s {{ {} }};""".format(','.join(biglist))) assert lib.nn0 == 0 assert lib.nn1234 == 1234 assert lib.nn5999 == 5999 diff --git a/testing/cffi1/test_verify1.py b/testing/cffi1/test_verify1.py index 9483d913e..629335948 100644 --- a/testing/cffi1/test_verify1.py +++ b/testing/cffi1/test_verify1.py @@ -134,7 +134,7 @@ def test_strlen_approximate(): def test_return_approximate(): for typename in ['short', 'int', 'long', 'long long']: ffi = FFI() - ffi.cdef("%s foo(signed char x);" % typename) + ffi.cdef(f"{typename} foo(signed char x);") lib = ffi.verify("signed char foo(signed char x) { return x;}") assert lib.foo(-128) == -128 assert lib.foo(+127) == +127 @@ -234,13 +234,12 @@ def test_all_integer_and_float_types(): typenames.append(typename) # ffi = FFI() - ffi.cdef('\n'.join(["%s foo_%s(%s);" % (tp, tp.replace(' ', '_'), tp) + ffi.cdef('\n'.join(["{} foo_{}({});".format(tp, tp.replace(' ', '_'), tp) for tp in typenames])) - lib = ffi.verify('\n'.join(["%s foo_%s(%s x) { return (%s)(x+1); }" % - (tp, tp.replace(' ', '_'), tp, tp) + lib = ffi.verify('\n'.join(["{} foo_{}({} x) {{ return ({})(x+1); }}".format(tp, tp.replace(' ', '_'), tp, tp) for tp in typenames])) for typename in typenames: - foo = getattr(lib, 'foo_%s' % typename.replace(' ', '_')) + foo = getattr(lib, 'foo_{}'.format(typename.replace(' ', '_'))) assert foo(42) == 43 if sys.version < '3': assert foo(long(44)) == 45 @@ -267,14 +266,13 @@ def test_all_complex_types(): header = '' # ffi = FFI() - ffi.cdef('\n'.join(["%s foo_%s(%s);" % (tp, tp.replace(' ', '_'), tp) + ffi.cdef('\n'.join(["{} foo_{}({});".format(tp, tp.replace(' ', '_'), tp) for tp in typenames])) lib = ffi.verify( - header + '\n'.join(["%s foo_%s(%s x) { return x; }" % - (tp, tp.replace(' ', '_'), tp) + header + '\n'.join(["{} foo_{}({} x) {{ return x; }}".format(tp, tp.replace(' ', '_'), tp) for tp in typenames])) for typename in typenames: - foo = getattr(lib, 'foo_%s' % typename.replace(' ', '_')) + foo = getattr(lib, 'foo_{}'.format(typename.replace(' ', '_'))) assert foo(42 + 1j) == 42 + 1j assert foo(ffi.cast(typename, 46 - 3j)) == 46 - 3j pytest.raises(TypeError, foo, ffi.NULL) @@ -282,12 +280,12 @@ def test_all_complex_types(): def test_var_signed_integer_types(): ffi = FFI() lst = all_signed_integer_types(ffi) - csource = "\n".join(["static %s somevar_%s;" % (tp, tp.replace(' ', '_')) + csource = "\n".join(["static {} somevar_{};".format(tp, tp.replace(' ', '_')) for tp in lst]) ffi.cdef(csource) lib = ffi.verify(csource) for tp in lst: - varname = 'somevar_%s' % tp.replace(' ', '_') + varname = 'somevar_{}'.format(tp.replace(' ', '_')) sz = ffi.sizeof(tp) max = (1 << (8*sz-1)) - 1 min = -(1 << (8*sz-1)) @@ -301,12 +299,12 @@ def test_var_signed_integer_types(): def test_var_unsigned_integer_types(): ffi = FFI() lst = all_unsigned_integer_types(ffi) - csource = "\n".join(["static %s somevar_%s;" % (tp, tp.replace(' ', '_')) + csource = "\n".join(["static {} somevar_{};".format(tp, tp.replace(' ', '_')) for tp in lst]) ffi.cdef(csource) lib = ffi.verify(csource) for tp in lst: - varname = 'somevar_%s' % tp.replace(' ', '_') + varname = 'somevar_{}'.format(tp.replace(' ', '_')) sz = ffi.sizeof(tp) if tp != '_Bool': max = (1 << (8*sz)) - 1 @@ -322,14 +320,13 @@ def test_var_unsigned_integer_types(): def test_fn_signed_integer_types(): ffi = FFI() lst = all_signed_integer_types(ffi) - cdefsrc = "\n".join(["%s somefn_%s(%s);" % (tp, tp.replace(' ', '_'), tp) + cdefsrc = "\n".join(["{} somefn_{}({});".format(tp, tp.replace(' ', '_'), tp) for tp in lst]) ffi.cdef(cdefsrc) - verifysrc = "\n".join(["%s somefn_%s(%s x) { return x; }" % - (tp, tp.replace(' ', '_'), tp) for tp in lst]) + verifysrc = "\n".join(["{} somefn_{}({} x) {{ return x; }}".format(tp, tp.replace(' ', '_'), tp) for tp in lst]) lib = ffi.verify(verifysrc) for tp in lst: - fnname = 'somefn_%s' % tp.replace(' ', '_') + fnname = 'somefn_{}'.format(tp.replace(' ', '_')) sz = ffi.sizeof(tp) max = (1 << (8*sz-1)) - 1 min = -(1 << (8*sz-1)) @@ -342,14 +339,13 @@ def test_fn_signed_integer_types(): def test_fn_unsigned_integer_types(): ffi = FFI() lst = all_unsigned_integer_types(ffi) - cdefsrc = "\n".join(["%s somefn_%s(%s);" % (tp, tp.replace(' ', '_'), tp) + cdefsrc = "\n".join(["{} somefn_{}({});".format(tp, tp.replace(' ', '_'), tp) for tp in lst]) ffi.cdef(cdefsrc) - verifysrc = "\n".join(["%s somefn_%s(%s x) { return x; }" % - (tp, tp.replace(' ', '_'), tp) for tp in lst]) + verifysrc = "\n".join(["{} somefn_{}({} x) {{ return x; }}".format(tp, tp.replace(' ', '_'), tp) for tp in lst]) lib = ffi.verify(verifysrc) for tp in lst: - fnname = 'somefn_%s' % tp.replace(' ', '_') + fnname = 'somefn_{}'.format(tp.replace(' ', '_')) sz = ffi.sizeof(tp) if tp != '_Bool': max = (1 << (8*sz)) - 1 @@ -423,12 +419,12 @@ def test_verify_typedefs(): for cdefed in types: for real in types: ffi = FFI() - ffi.cdef("typedef %s foo_t;" % cdefed) + ffi.cdef(f"typedef {cdefed} foo_t;") if cdefed == real: - ffi.verify("typedef %s foo_t;" % real) + ffi.verify(f"typedef {real} foo_t;") else: pytest.raises(VerificationError, ffi.verify, - "typedef %s foo_t;" % real) + f"typedef {real} foo_t;") def test_nondecl_struct(): ffi = FFI() @@ -509,22 +505,22 @@ def _check_field_match(typename, real, expect_mismatch): testing_by_size = (expect_mismatch == 'by_size') if testing_by_size: expect_mismatch = ffi.sizeof(typename) != ffi.sizeof(real) - ffi.cdef("struct foo_s { %s x; ...; };" % typename) + ffi.cdef(f"struct foo_s {{ {typename} x; ...; }};") try: - ffi.verify("struct foo_s { %s x; };" % real) + ffi.verify(f"struct foo_s {{ {real} x; }};") ffi.new("struct foo_s *", []) # because some mismatches show up lazily except (VerificationError, ffi.error): if not expect_mismatch: if testing_by_size and typename != real: - print("ignoring mismatch between %s* and %s* even though " - "they have the same size" % (typename, real)) + print(f"ignoring mismatch between {typename}* and {real}* even though " + "they have the same size") return - raise AssertionError("unexpected mismatch: %s should be accepted " - "as equal to %s" % (typename, real)) + raise AssertionError(f"unexpected mismatch: {typename} should be accepted " + f"as equal to {real}") else: if expect_mismatch: raise AssertionError("mismatch not detected: " - "%s != %s" % (typename, real)) + f"{typename} != {real}") def test_struct_bad_sized_integer(): for typename in ['int8_t', 'int16_t', 'int32_t', 'int64_t']: @@ -704,7 +700,7 @@ def test_global_const_int_size(): else: raise AssertionError(value) ffi.cdef("static const unsigned short AA;") - lib = ffi.verify("#define AA %s\n" % vstr) + lib = ffi.verify(f"#define AA {vstr}\n") assert lib.AA == value assert type(lib.AA) is type(int(lib.AA)) @@ -837,7 +833,7 @@ def test_access_address_of_variable(): def test_access_array_variable(length=5): ffi = FFI() ffi.cdef("static int foo(int);\n" - "static int somenumber[%s];" % (length,)) + f"static int somenumber[{length}];") lib = ffi.verify(""" static int somenumber[] = {2, 2, 3, 4, 5}; static int foo(int i) { @@ -852,7 +848,7 @@ def test_access_array_variable(length=5): assert repr(lib.somenumber).startswith(" Date: Sun, 19 Jul 2026 22:59:50 +0200 Subject: [PATCH 2/2] Apply ruff/pyupgrade rule UP031 These are manual fixes --- testing/cffi1/test_new_ffi_1.py | 16 +++++++--------- testing/cffi1/test_parse_c_type.py | 8 ++++---- testing/cffi1/test_recompiler.py | 12 ++++++------ testing/cffi1/test_verify1.py | 18 +++++++++--------- 4 files changed, 26 insertions(+), 28 deletions(-) diff --git a/testing/cffi1/test_new_ffi_1.py b/testing/cffi1/test_new_ffi_1.py index baa25b6bd..d4a362dba 100644 --- a/testing/cffi1/test_new_ffi_1.py +++ b/testing/cffi1/test_new_ffi_1.py @@ -119,8 +119,8 @@ def test_integer_ranges(self): def test_fixedsize_int(self): for size in [1, 2, 4, 8]: - self._test_int_type(ffi, 'int%d_t' % (8*size), size, False) - self._test_int_type(ffi, 'uint%d_t' % (8*size), size, True) + self._test_int_type(ffi, f'int{8*size}_t', size, False) + self._test_int_type(ffi, f'uint{8*size}_t', size, True) self._test_int_type(ffi, 'intptr_t', SIZE_OF_PTR, False) self._test_int_type(ffi, 'uintptr_t', SIZE_OF_PTR, True) self._test_int_type(ffi, 'ptrdiff_t', SIZE_OF_PTR, False) @@ -288,10 +288,10 @@ def test_repr(self): assert repr(ffi.typeof(p)) == typerepr % "int *" # p = ffi.new("int*") - assert repr(p) == "" % SIZE_OF_INT + assert repr(p) == f"" assert repr(ffi.typeof(p)) == typerepr % "int *" p = ffi.new("int**") - assert repr(p) == "" % SIZE_OF_PTR + assert repr(p) == f"" assert repr(ffi.typeof(p)) == typerepr % "int * *" p = ffi.new("int [2]") assert repr(p) == "" % (2*SIZE_OF_INT) @@ -575,8 +575,7 @@ def test_union_simple(self): assert u.a == -2 with pytest.raises((AttributeError, TypeError)): del u.a - assert repr(u) == "" % ( - SIZE_OF_INT,) + assert repr(u) == f"" def test_union_opaque(self): pytest.raises(ffi.error, ffi.new, "union baz*") @@ -732,8 +731,7 @@ def cb(n): "" % ( - SIZE_OF_PTR) + assert repr(q) == f"" with pytest.raises(TypeError): q(43) res = q[0](43) @@ -984,7 +982,7 @@ def test_array_of_struct(self): def test_pointer_to_array(self): p = ffi.new("int(**)[5]") - assert repr(p) == "" % SIZE_OF_PTR + assert repr(p) == f"" def test_iterate_array(self): a = ffi.new("char[]", b"hello") diff --git a/testing/cffi1/test_parse_c_type.py b/testing/cffi1/test_parse_c_type.py index 6d9efbd33..52f4737a4 100644 --- a/testing/cffi1/test_parse_c_type.py +++ b/testing/cffi1/test_parse_c_type.py @@ -131,7 +131,7 @@ def parsex(input): def str_if_int(x): if isinstance(x, str): return x - return '%d,%d' % (x & 255, x >> 8) + return f'{x & 255},{x >> 8}' return ' '.join(map(str_if_int, result)) def parse_error(input, expected_msg, expected_location): @@ -302,9 +302,9 @@ def test_error(): def test_number_too_large(): num_max = sys.maxsize - assert parse("char[%d]" % num_max) == [Prim(lib._CFFI_PRIM_CHAR), - '->', Array(0), num_max] - parse_error("char[%d]" % (num_max + 1), "number too large", 5) + assert parse(f"char[{num_max}]") == [Prim(lib._CFFI_PRIM_CHAR), + '->', Array(0), num_max] + parse_error(f"char[{num_max + 1}]", "number too large", 5) def test_complexity_limit(): parse_error("int" + "[]" * 2500, "internal type complexity limit reached", diff --git a/testing/cffi1/test_recompiler.py b/testing/cffi1/test_recompiler.py index 06e615c00..b473b2dfc 100644 --- a/testing/cffi1/test_recompiler.py +++ b/testing/cffi1/test_recompiler.py @@ -231,12 +231,12 @@ def test_macro_check_value(): if sys.maxsize <= 2**32 or sys.platform == 'win32': vals.remove('-2147483648') ffi = FFI() - cdef_lines = ['#define FOO_%d_%d %s' % (i, j, vals[i]) + cdef_lines = [f'#define FOO_{i}_{i} {vals[i]}' for i in range(len(vals)) for j in range(len(vals))] ffi.cdef('\n'.join(cdef_lines)) - verify_lines = ['#define FOO_%d_%d %s' % (i, j, vals[j]) # [j], not [i] + verify_lines = [f'#define FOO_{i}_{j} {vals[j]}' # [j], not [i] for i in range(len(vals)) for j in range(len(vals))] lib = verify(ffi, 'test_macro_check_value_ok', @@ -249,7 +249,7 @@ def test_macro_check_value(): c_compiler_msg += f' (0x{c_got:x})' # for i in range(len(vals)): - attrname = 'FOO_%d_%d' % (i, j) + attrname = f'FOO_{i}_{j}' if i == j: x = getattr(lib, attrname) assert x == c_got @@ -510,9 +510,9 @@ def test_verify_anonymous_enum_with_typedef(): assert repr(ffi.cast("e1", 2)) == "" # ffi = FFI() - ffi.cdef("typedef enum { AA=%d } e1;" % sys.maxsize) + ffi.cdef(f"typedef enum {{ AA={sys.maxsize} }} e1;") lib = verify(ffi, 'test_verify_anonymous_enum_with_typedef2', - "typedef enum { AA=%d } e1;" % sys.maxsize) + f"typedef enum {{ AA={sys.maxsize} }} e1;") assert lib.AA == int(ffi.cast("long", sys.maxsize)) assert ffi.sizeof("e1") == ffi.sizeof("long") @@ -2579,7 +2579,7 @@ def test_convert_api_mode_builtin_function_to_cdata(): def test_large_enum(): ffi = FFI() - biglist = ['nn%d' % i for i in range(6000)] + biglist = [f'nn{i}' for i in range(6000)] ffi.cdef( """enum foo_s {{ {} }};""".format(','.join(biglist))) lib = verify(ffi, "test_large_enum", """ diff --git a/testing/cffi1/test_verify1.py b/testing/cffi1/test_verify1.py index 629335948..51590c78a 100644 --- a/testing/cffi1/test_verify1.py +++ b/testing/cffi1/test_verify1.py @@ -26,7 +26,7 @@ class FFI(FFI): def verify(self, preamble='', *args, **kwds): # HACK to reuse the tests from ../cffi0/test_verify.py FFI._verify_counter += 1 - module_name = 'verify%d' % FFI._verify_counter + module_name = f'verify{FFI._verify_counter}' try: del self._assigned_source except AttributeError: @@ -692,11 +692,11 @@ def test_global_const_int_size(): ffi = FFI() if value == int(ffi.cast("long long", value)): if value < 0: - vstr = '(-%dLL-1)' % (~value,) + vstr = f'(-{~value}LL-1)' else: - vstr = '%dLL' % value + vstr = f'{value}LL' elif value == int(ffi.cast("unsigned long long", value)): - vstr = '%dULL' % value + vstr = f'{value}ULL' else: raise AssertionError(value) ffi.cdef("static const unsigned short AA;") @@ -1734,10 +1734,10 @@ def test_enum_size(): ('-2147483647-1', 4, -1), ] if FFI().sizeof("long") == 8: - cases += [('4294967296L', 8, 2**64-1), - ('%dUL' % (2**64-1), 8, 2**64-1), - ('-2147483649L', 8, -1), - ('%dL-1L' % (1-2**63), 8, -1)] + cases += [('4294967296L', 8, 2**64-1), + (f'{2**64-1}UL', 8, 2**64-1), + ('-2147483649L', 8, -1), + (f'{1-2**63}L-1L', 8, -1)] for hidden_value, expected_size, expected_minus1 in cases: if sys.platform == 'win32' and 'U' in hidden_value: continue # skipped on Windows @@ -1754,7 +1754,7 @@ def test_enum_size(): ## for hidden_value, expected_size, expected_minus1 in cases: ## ffi = FFI() ## ffi.cdef("enum foo_e { AA, BB, ... };") -## lib = ffi.verify("enum foo_e { AA, BB=%s };" % hidden_value) +## lib = ffi.verify(f"enum foo_e {{ AA, BB={hidden_value} }};") ## assert lib.AA == 0 ## assert ffi.sizeof("enum foo_e") == expected_size ## assert int(ffi.cast("enum foo_e", -1)) == expected_minus1