Typing Stubs for cffi
types-cffi is a type stub package providing external type annotations for the popular `cffi` library, which allows Python to call C code. It enables static type checkers like MyPy and PyRight to analyze code that uses `cffi` for improved development experience and bug detection. This package is part of the broader typeshed project and is regularly updated, with releases potentially occurring daily, to maintain compatibility with `cffi` itself.
Warnings
- gotcha Installing `types-cffi` does not install the `cffi` runtime library. `types-cffi` only provides type annotations. You must install `cffi` separately (e.g., `pip install cffi`) for your code to run.
- breaking `types-cffi` versions are aligned with `cffi` runtime versions. For example, `types-cffi==2.0.x.YYYYMMDD` provides stubs for `cffi==2.0.*`. Using significantly mismatched versions (e.g., `types-cffi` for `cffi` 2.0 with a `cffi` 1.x runtime) can lead to incorrect type checking results or missed errors.
- deprecated The behavior of `ffi.new_handle()` changed in `cffi` v1.3.1 to guarantee unique `void *` values, even when called on the same object multiple times. Code relying on previous CPython behavior (where it might return two `cdata` objects with the same `void *` value) could break if not keeping the result of `ffi.new_handle()` alive explicitly.
- breaking For `cffi` projects targeting Python 3.12 and newer, if they utilize `cffi` features that historically depended on `distutils` (which was removed in Python 3.12), they must explicitly add `setuptools` as a dependency. `cffi` itself does not add this runtime dependency to avoid unnecessary installs for projects that don't need it.
- gotcha While typeshed aims to minimize breaking changes in stubs, any update to `types-cffi` (or any `types-*` package) can introduce changes that might cause your code to fail type checking, even if the runtime behavior of `cffi` hasn't changed. This is inherent to the evolving nature of type annotations.
Install
-
pip install types-cffi -
pip install cffi
Imports
- FFI
from cffi import FFI
- lib
from cffi import lib
Quickstart
import os
from cffi import FFI
# Initialize FFI
ffi = FFI()
# Declare C functions (e.g., from the standard C library)
ffi.cdef("""int puts(const char* s);""")
# Load the C library (None on Unix-like systems typically opens libc)
try:
libc = ffi.dlopen(None) # type: ignore
except OSError:
print("Could not load libc. This example might not run on all systems.\n"\
"Ensure a C standard library is available and discoverable.")
exit(1)
# Call a C function with type checking (implicitly using types-cffi)
message = ffi.new("char[]", b"Hello from C via CFFI and types-cffi!")
return_code = libc.puts(message)
print(f"C puts() returned: {return_code}")
# Example of type checking at development time:
# If you misspelled 'puts' or passed an int instead of bytes,
# a type checker (like MyPy) would flag it due to types-cffi.