Allow writing generated code to a file-like object. by inklesspen · Pull Request #115 · python-cffi/cffi · GitHub
Skip to content
Merged
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
12 changes: 12 additions & 0 deletions doc/source/cdef.rst
10 changes: 10 additions & 0 deletions src/cffi/recompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1419,13 +1419,20 @@ def write(self, s):
s = s.encode('ascii')
super(NativeIO, self).write(s)

def _is_file_like(maybefile):
# compare to xml.etree.ElementTree._get_writer
return hasattr(maybefile, 'write')

def _make_c_or_py_source(ffi, module_name, preamble, target_file, verbose):
if verbose:
print("generating %s" % (target_file,))
recompiler = Recompiler(ffi, module_name,
target_is_python=(preamble is None))
recompiler.collect_type_table()
recompiler.collect_step_tables()
if _is_file_like(target_file):
recompiler.write_source_to_f(target_file, preamble)
return True
f = NativeIO()
recompiler.write_source_to_f(f, preamble)
output = f.getvalue()
Expand Down Expand Up @@ -1526,6 +1533,9 @@ def recompile(ffi, module_name, preamble, tmpdir='.', call_c_compiler=True,
if ffi._windows_unicode:
ffi._apply_windows_unicode(kwds)
if preamble is not None:
if call_c_compiler and _is_file_like(c_file):
raise TypeError("Writing to file-like objects is not supported "
"with call_c_compiler=True")
embedding = (ffi._embedding is not None)
if embedding:
ffi._apply_embedding_fix(kwds)
Expand Down
9 changes: 8 additions & 1 deletion testing/cffi1/test_new_ffi_1.py