soundstripe
soundstripe

Reputation: 1474

Python `inspect.stack()` returns FrameInfo objects with missing `code_context` at the REPL

When using Python's REPL/interactive prompt, the objects returned by inspect.stack() always have .code_context set to None.

The same code executed from within a .py file returns the code line by line in a stack trace as expected.

>>> import inspect
>>> print(inspect.stack()[0].code_context)
None

same code executed within a .py file prints:

['print(inspect.stack()[0].code_context)\n']

Upvotes: 0

Views: 1126

Answers (1)

soundstripe
soundstripe

Reputation: 1474

Posting comment from @jasonharper as the answer here. Thanks!

The only way that the inspect module can display source code is if the code came from a file that it can access. Source typed at an interactive prompt is discarded as soon as it is parsed, there's simply no way for inspect to access it. – @jasonharper

Upvotes: 1

Related Questions