0

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']

2
  • 1
    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. Commented Aug 10, 2020 at 20:38
  • I was afraid of that! Commented Aug 10, 2020 at 20:42

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.