Python 3.8+iofunction
io.open_code
utilities
Opens a file for reading as executable code, honouring security audit hooks; prefer it over open() for loading code (Python 3.8+).
Syntax
io.open_code(path)
It is always a binary read: mode 'rb', no encoding or newline arguments, and path is expected to be an absolute string. The call itself validates nothing and adds no security by itself — its value is being a single interception point, so an application or embedder can replace it (or attach an audit hook) and refuse, say, an unsigned file. The import machinery reads the code it is about to execute through the same entry point.
Examples
import io
import json
print(callable(io.open_code)) # → True
with io.open_code(json.__file__) as f: print(f.mode, type(f).__name__) # → rb BufferedReader
print(io.open_code('no_such_file.py')) # → FileNotFoundError
print(io.open_code('script.py', 'w')) # → TypeError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy