- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Interpreter base classes in Python
Python's interactive mode works on the principle of REPL (Read - Evaluate - Print - Loop). The code module in Python's standard library provides classes nd convenience functions to set up REPL environment from within Python script.
Following two classes are defined in code module:
InteractiveInterpreter: This class deals with parsing and interpreter state (the user’s namespace)
InteractiveConsole: Closely emulate the behavior of the interactive Python interpreter.
Two convenience functions in the module are:
interact(): Convenience function to run a read-eval-print loop.
compile_command(): This function is useful for programs that want to emulate Python’s interpreter main loop (the REPL).
Interactive Interpreter methods
runsource(): Compile and run some source in the interpreter.
runcode(): Execute a code object
Interactive Console methods:
Because the InteractiveConsole class is a subclass of InteractiveInterpreter, above methods are automatically available. Additionally following methods are defined.
interact(): Closely emulate the interactive Python console.
push(): Push a line of source text to the interpreter.
resetbuffer(): Remove any unhandled source text from the input buffer.
Write a prompt and read a line by defaultfrom sys.stdin
import code x = 10 y = 20 def add(x,y): return x+y print (add(x,y)) code.interact(local=locals()) print (x,y) print (add(x,y))
In the above code, two vaiables are defined and passed to a function. The we invoke he interactive console. The argument local=locals() allows use of local namespace as the default within the interpreter loop.
If you assign different values to variables and exit the console by pressing ctrl+D, those values are now passed to the function
addition= 30 Python 3.6.6 |Anaconda custom (64-bit)| (default, Oct 9 2018, 12:34:16) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> x=100 >>> y=200 >>> now exiting InteractiveConsole... 100 200 addition = 300
- Python Exception Base Classes
- Abstract Base Classes in Python (abc)
- Python Abstract Base Classes for Containers
- What are Base and Derived Classes in C#?
- Catching base and derived classes exceptions in C++
- What is the Python Global Interpreter Lock (GIL)
- Creating Classes in Python
- Difference Between Compiler and Interpreter
- Data Classes in Python (dataclasses)
- Is JVM a compiler or interpreter?
- Base Overloading Methods in Python
- Smallest Good Base in Python
- How to define classes in Python?
- What to do to become an interpreter?
- How to view a list of all Python operators via the interpreter?