Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions demo/_curses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand All @@ -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

Expand Down
7 changes: 3 additions & 4 deletions demo/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion demo/gmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 13 additions & 18 deletions src/c/test_c.py
Original file line number Diff line number Diff line change
Expand Up @@ -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) == "<cdata 'signed char' -65>"
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) == "<cdata 'signed char' -66>"
Expand Down Expand Up @@ -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')) == "<cdata 'char' %s'A'>" % mandatory_b_prefix
assert repr(cast(p, 255)) == r"<cdata 'char' %s'\xff'>" % mandatory_b_prefix
assert repr(cast(p, 0)) == r"<cdata 'char' %s'\x00'>" % mandatory_b_prefix
assert repr(cast(p, 'A')) == f"<cdata 'char' {mandatory_b_prefix}'A'>"
assert repr(cast(p, 255)) == rf"<cdata 'char' {mandatory_b_prefix}'\xff'>"
assert repr(cast(p, 0)) == rf"<cdata 'char' {mandatory_b_prefix}'\x00'>"

def test_pointer_type():
p = new_primitive_type("int")
Expand Down Expand Up @@ -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)) == "<cdata '%s' %s'E'>" % (
typename, mandatory_u_prefix)
assert str(cast(BWChar, 0x1234)) == "<cdata '%s' %s'\u1234'>" % (
typename, mandatory_u_prefix)
assert str(cast(BWChar, 0x45)) == f"<cdata '{typename}' {mandatory_u_prefix}'E'>"
assert str(cast(BWChar, 0x1234)) == f"<cdata '{typename}' {mandatory_u_prefix}'\u1234'>"
if not _hacked_pypy_uni4():
if wchar4:
x = cast(BWChar, 0x12345)
assert str(x) == "<cdata '%s' %s'\U00012345'>" % (
typename, mandatory_u_prefix)
assert str(x) == f"<cdata '{typename}' {mandatory_u_prefix}'\U00012345'>"
assert int(x) == 0x12345
else:
x = cast(BWChar, 0x18345)
assert str(x) == "<cdata '%s' %s'\u8345'>" % (
typename, mandatory_u_prefix)
assert str(x) == f"<cdata '{typename}' {mandatory_u_prefix}'\u8345'>"
assert int(x) == 0x8345
#
BWCharP = new_pointer_type(BWChar)
Expand Down Expand Up @@ -2288,26 +2284,25 @@ def _test_wchar_variant(typename):
a[4]
#
w = cast(BWChar, 'a')
assert repr(w) == "<cdata '%s' %s'a'>" % (typename, mandatory_u_prefix)
assert repr(w) == f"<cdata '{typename}' {mandatory_u_prefix}'a'>"
assert str(w) == repr(w)
assert string(w) == u+'a'
assert int(w) == ord('a')
w = cast(BWChar, 0x1234)
assert repr(w) == "<cdata '%s' %s'\u1234'>" % (typename, mandatory_u_prefix)
assert repr(w) == f"<cdata '{typename}' {mandatory_u_prefix}'\u1234'>"
assert str(w) == repr(w)
assert string(w) == u+'\u1234'
assert int(w) == 0x1234
w = cast(BWChar, u+'\u8234')
assert repr(w) == "<cdata '%s' %s'\u8234'>" % (typename, mandatory_u_prefix)
assert repr(w) == f"<cdata '{typename}' {mandatory_u_prefix}'\u8234'>"
assert str(w) == repr(w)
assert string(w) == u+'\u8234'
assert int(w) == 0x8234
w = cast(BInt, u+'\u1234')
assert repr(w) == "<cdata 'int' 4660>"
if wchar4 and not _hacked_pypy_uni4():
w = cast(BWChar, u+'\U00012345')
assert repr(w) == "<cdata '%s' %s'\U00012345'>" % (
typename, mandatory_u_prefix)
assert repr(w) == f"<cdata '{typename}' {mandatory_u_prefix}'\U00012345'>"
assert str(w) == repr(w)
assert string(w) == u+'\U00012345'
assert int(w) == 0x12345
Expand Down Expand Up @@ -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("<cdata '%s *' 0x" % typename)
assert repr(p).startswith(f"<cdata '{typename} *' 0x")
return len(string(p))
BFunc = new_function_type((BWCharP,), BInt, False)
f = callback(BFunc, cb, -42)
Expand Down
8 changes: 4 additions & 4 deletions src/cffi/_cffi_gen_src.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,17 +75,17 @@ def find_ffi_in_python_script(pysrc, filename, ffivar):
_execfile(pysrc, filename, globs)
if ffivar not in globs:
raise NameError(
"Expected to find the FFI object with the name %r, "
"but it was not found." % (ffivar,)
f"Expected to find the FFI object with the name {ffivar!r}, "
"but it was not found."
)
ffi = globs[ffivar]
if not isinstance(ffi, FFI) and callable(ffi):
# Maybe it's a callable that returns a FFI
ffi = ffi()
if not isinstance(ffi, FFI):
raise TypeError(
"Found an object with the name %r but it was not an "
"instance of cffi.api.FFI" % (ffivar,)
f"Found an object with the name {ffivar!r} but it was not an "
"instance of cffi.api.FFI"
)
return ffi
finally:
Expand Down
4 changes: 2 additions & 2 deletions src/cffi/_imp_emulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ def get_suffixes():

def find_module(name, path=None):
if not isinstance(name, str):
raise TypeError("'name' must be a str, not {}".format(type(name)))
raise TypeError(f"'name' must be a str, not {type(name)}")
elif not isinstance(path, (type(None), list)):
# Backwards-compatibility
raise RuntimeError("'path' must be None or a list, "
"not {}".format(type(path)))
f"not {type(path)}")

if path is None:
if is_builtin(name):
Expand Down
34 changes: 15 additions & 19 deletions src/cffi/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,10 @@ def __init__(self, backend=None):
# bad version! Try to be as explicit as possible.
if hasattr(backend, '__file__'):
# CPython
raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. When we import the top-level '_cffi_backend' extension module, we get version %s, located in %r. The two versions should be equal; check your installation." % (
__version__, __file__,
backend.__version__, backend.__file__))
raise Exception(f"Version mismatch: this is the 'cffi' package version {__version__}, located in {__file__!r}. When we import the top-level '_cffi_backend' extension module, we get version {backend.__version__}, located in {backend.__file__!r}. The two versions should be equal; check your installation.")
else:
# PyPy
raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. This interpreter comes with a built-in '_cffi_backend' module, which is version %s. The two versions should be equal; check your installation." % (
__version__, __file__, backend.__version__))
raise Exception(f"Version mismatch: this is the 'cffi' package version {__version__}, located in {__file__!r}. This interpreter comes with a built-in '_cffi_backend' module, which is version {backend.__version__}. The two versions should be equal; check your installation.")
# (If you insist you can also try to pass the option
# 'backend=backend_ctypes.CTypesBackend()', but don't
# rely on it! It's probably not going to work well.)
Expand Down Expand Up @@ -180,8 +177,8 @@ def _typeof(self, cdecl, consider_function_as_funcptr=False):
#
btype, really_a_function_type = result
if really_a_function_type and not consider_function_as_funcptr:
raise CDefError("the type %r is a function type, not a "
"pointer-to-function type" % (cdecl,))
raise CDefError(f"the type {cdecl!r} is a function type, not a "
"pointer-to-function type")
return btype

def typeof(self, cdecl):
Expand Down Expand Up @@ -406,7 +403,7 @@ def getctype(self, cdecl, replace_with=''):
replace_with = replace_with.strip()
if (replace_with.startswith('*')
and '&[' in self._backend.getcname(cdecl, '&')):
replace_with = '(%s)' % replace_with
replace_with = f'({replace_with})'
elif replace_with and replace_with[0] not in '[(':
replace_with = ' ' + replace_with
return self._backend.getcname(cdecl, replace_with)
Expand Down Expand Up @@ -518,8 +515,7 @@ def include(self, ffi_to_include):
"""
if not isinstance(ffi_to_include, FFI):
raise TypeError("ffi.include() expects an argument that is also of"
" type cffi.FFI, not %r" % (
type(ffi_to_include).__name__,))
f" type cffi.FFI, not {type(ffi_to_include).__name__!r}")
if ffi_to_include is self:
raise ValueError("self.include(self)")
with ffi_to_include._lock:
Expand Down Expand Up @@ -589,7 +585,7 @@ def ensure(key, value):
if sys.platform == "win32":
# we need 'libpypy-c.lib'. Current distributions of
# pypy (>= 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:
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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()
Expand All @@ -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()
Expand Down
Loading
Loading