Skip to content

Commit

Permalink
Backport PR #12809: Allow passing a custom CachingCompiler to the int…
Browse files Browse the repository at this point in the history
…eractive shell
  • Loading branch information
SylvainCorlay authored and meeseeksmachine committed Feb 19, 2021
1 parent 9c40b71 commit 3d73b3e
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 74 deletions.
44 changes: 36 additions & 8 deletions IPython/core/compilerop.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def ast_parse(self, source, filename='<unknown>', symbol='exec'):
Arguments are exactly the same as ast.parse (in the standard library),
and are passed to the built-in compile function."""
return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)

def reset_compiler_flags(self):
"""Reset compiler flags to default state."""
# This value is copied from codeop.Compile.__init__, so if that ever
Expand All @@ -112,25 +112,53 @@ def compiler_flags(self):
"""
return self.flags

def cache(self, code, number=0):
def get_code_name(self, raw_code, transformed_code, number):
"""Compute filename given the code, and the cell number.
Parameters
----------
raw_code : str
The raw cell code.
transformed_code : str
The executable Python source code to cache and compile.
number : int
A number which forms part of the code's name. Used for the execution
counter.
Returns
-------
The computed filename.
"""
return code_name(transformed_code, number)

def cache(self, transformed_code, number=0, raw_code=None):
"""Make a name for a block of code, and cache the code.
Parameters
----------
code : str
The Python source code to cache.
transformed_code : str
The executable Python source code to cache and compile.
number : int
A number which forms part of the code's name. Used for the execution
counter.
raw_code : str
The raw code before transformation, if None, set to `transformed_code`.
Returns
-------
The name of the cached code (as a string). Pass this as the filename
argument to compilation, so that tracebacks are correctly hooked up.
"""
name = code_name(code, number)
entry = (len(code), time.time(),
[line+'\n' for line in code.splitlines()], name)
if raw_code is None:
raw_code = transformed_code

name = self.get_code_name(raw_code, transformed_code, number)
entry = (
len(transformed_code),
time.time(),
[line + "\n" for line in transformed_code.splitlines()],
name,
)
linecache.cache[name] = entry
linecache._ipython_cache[name] = entry
return name
Expand All @@ -146,7 +174,7 @@ def extra_flags(self, flags):
yield
finally:
# turn off only the bits we turned on so that something like
# __future__ that set flags stays.
# __future__ that set flags stays.
self.flags &= ~turn_on_bits


Expand Down
Loading

0 comments on commit 3d73b3e

Please sign in to comment.