Typing Stubs for aiofiles
types-aiofiles provides type stubs for the aiofiles library, enabling static type checkers like MyPy and Pyright to verify code that uses aiofiles. It is part of the typeshed project and is regularly updated, with version 25.1.0.20251011 aiming for aiofiles==25.1.*.
Warnings
- gotcha Stub versions are designed for specific runtime library versions (e.g., `types-aiofiles==25.1.0.20251011` for `aiofiles==25.1.*`). Mismatches can lead to incorrect type checking results or missed type errors.
- breaking This package provides *only* type stubs (`.pyi` files) for `aiofiles`, not the runtime library itself. You still need to install `aiofiles` (`pip install aiofiles`) to use its functionality. Attempting to run code with only `types-aiofiles` installed will result in `ModuleNotFoundError` for `aiofiles`.
- gotcha Do not attempt to import symbols directly from `types-aiofiles` in your runtime code. It is purely for static type checking; all runtime imports should come from the `aiofiles` package (e.g., `import aiofiles`, `import aiofiles.os`).
- gotcha A known issue in `typeshed` (and thus `types-aiofiles`) involved `aiofiles.tempfile.NamedTemporaryFile.name` being incorrectly typed as `FileDescriptorOrPath` instead of `str`. While potentially fixed in newer stub versions, verify with your type checker if you encounter issues when accessing the `.name` attribute.
Install
-
pip install types-aiofiles -
pip install aiofiles types-aiofiles
Imports
- open
import aiofiles async with aiofiles.open('file.txt', mode='r') as f: - os
import aiofiles.os await aiofiles.os.stat('file.txt')
Quickstart
import asyncio
import aiofiles
async def main():
# Write to a file asynchronously
async with aiofiles.open('example.txt', mode='w') as f:
await f.write('Hello, aiofiles!\n')
await f.write('This is an async file operation.')
print('Wrote to example.txt')
# Read from a file asynchronously
async with aiofiles.open('example.txt', mode='r') as f:
contents = await f.read()
print(f'Read from example.txt:\n{contents}')
# Clean up (optional)
import aiofiles.os
await aiofiles.os.remove('example.txt')
print('Cleaned up example.txt')
if __name__ == '__main__':
asyncio.run(main())