When you are working on a project or learning the language, the Python standard shell, often known as the REPL (Read-Eval-Print Loop), gives you the ability to execute Python code in an interactive manner. Because this utility is included with every Python installation, you are free to make use of it at any time.
Since this tool enables you to test new ideas, investigate and experiment with new tools and libraries, restructure and debug your code, and try out examples, as a Python developer you will spend a significant portion of your coding time in a REPL session. You will learn how to do the following at the end of this guide:
-
Run the Python
standard REPL
, or interactive shell -
Write and execute
Python code
in an interactive session -
Quickly
edit
,
modify
, and
reuse
code in a REPL session -
Get
help
and
introspect
your code in an interactive session -
Tweak
some features of the standard REPL -
Identify the standard REPL’s
missing features
You will also get an understanding of the several feature-rich REPLs that are available, such as IDLE, IPython, bpython, and ptpython.
You should have prior experience working with the command line or terminal of your operating system in order to get the most out of this tutorial. You should also be familiar with the fundamentals of running your program using the python command.
code.
Getting to Know the Python Standard REPL
Compiler languages and interpreter languages are the two primary categories of programming languages used in the field of computer programming. Compiler software is required for compiled programming languages such as C and C++. The compiler program is responsible for converting the language’s code into machine code.
In most cases, this machine code will be preserved inside an executable file. When you have your program in the form of an executable file, you may execute it on any computer system that is compatible with it; you do not need the compiler or the source code.
In contrast, interpreted languages such as Python need a separate piece of software known as an interpreter. This indicates that in order to execute Python code on your computer, you will need to have a Python interpreter already installed. Because of this feature’s potential to make the process of code distribution considerably more difficult, it is possible that some people may see it as a negative trait.
On the other hand, having an interpreter at your disposal in Python provides one big benefit that comes in handy while you’re working on the development and testing process. An interactive REPL (Read-Eval-Print Loop), also known as a shell, is made possible by the Python interpreter. This type of shell reads a section of code, performs an evaluation on that code, and then repeatedly prints the result of the evaluation to the console. Note: The CPython standard REPL, which is accessible in all of this Python distribution’s installers, will be covered in this lesson, and you will learn more about it as you go through it. If you don’t already have CPython, check out the Python 3 Installation & Setup Guide for step-by-step instructions on how to get it installed.
The Python interpreter is capable of running Python code in two different modes.
modes:
-
Script
, or program -
Interactive
, or REPL
While you are in script mode, the interpreter is used to execute a source file in the same manner as an executable program. In this scenario, Python reads the contents of the file and then executes the code one line at a time, following the execution flow of the script or program. On the other hand, interactive mode is when you start the interpreter and use it as a platform to execute code that you enter in directly. This mode is activated when you press the “Interact” button. Note that the term “Python” may refer to both the programming language and its associated interpreter. This is due to the fact that the word “Python” is often used to refer to both of these concepts. Only in those instances where there is a possibility of confusion will you see the word Python interpreter used explicitly within the context of this course.
Using the Python standard REPL, which you’ll learn how to do in this tutorial, you’ll be able to run code in an interactive manner, which gives you the opportunity to experiment with different ideas and concepts while using and learning Python. Are you prepared to have a look at the Python REPL in more detail? Keep
reading!
What Is Python’s Interactive Shell or REPL?
An interactive shell, also known as an interactive session or a REPL session, is opened whenever the Python interpreter is executed in the interactive mode. This mode is also known as the interactive mode. Your keyboard will serve as the input device for this shell, and the screen will be used as the destination for any output. Please take note that the definitions for these words may be found in this guide.
shell with interactive features,
session with audience participation,
session with the interpreter, as well as
REPL session is used interchangeably throughout this document.
Python code makes up the input, which is then processed through the interpreter so that it can be evaluated. When that step is finished, the result will be shown on your screen by the interpreter automatically, and the procedure will begin once again as a loop.
Hence, the REPL in Python is an interactive means to communicate with your computer by utilizing the Python programming language. It’s really similar to live chat. The entirety of the process is referred to as a REPL because it is broken down into four stages that fall under the
hood:
-
Reading
your input, which consists of Python code as
expressions
and
statements
-
Evaluating
your Python code, which generates a result or causes
side effects
-
Printing
any output so that you can check your code’s results and get immediate feedback -
Looping
back to step one to continue the interaction
This feature of Python is a potent instrument that you will end up requiring in your Python coding experience, particularly while you are learning the language or when you are in the early phases of a development process. This is due to the fact that the REPL provides a variety of advantages, all of which will be explained to you later.
next.
Why Use a Python REPL?
You may expect to spend a significant portion of your time as a Python coder in interactive mode. This mode offers a convenient and speedy method for testing out ideas and bits of code. You are free to do any number of the tasks listed below while connected to a REPL session.
tasks:
-
Explore and learn
Python syntax
-
Try out and prove
ideas
,
concepts
, and
implementations
-
Quickly evaluate
code snippets
-
Dive into the
language behaviors
-
Edit and
refactor
your code for later use in
script mode
-
Perform code and
type introspection
-
Get interactive
help
on how to use the language -
Run basic code
debugging
-
Explore standard-library and third-party
modules
,
libraries
, and
APIs
-
Inspect the implementation of
classes
,
functions
, and
other objects
As a Python developer, it is obvious that you will have many valid reasons to spend a significant portion of your time working interactively with the interpreter while logged into REPL sessions. The most important advantage of utilizing a REPL session is that it provides you with instant feedback on the operation of your code.
Python’s interactive mode is one of its most powerful and useful features. It gives you the ability to try out different solutions and experiment in real time with the language. If you are interested in how something operates, all you need to do is test it in an interactive shell.
Your prior experience in programming may have been with compiled languages that do not give a REPL; in this case, you should strongly consider the interactive shell a great learning tool. This is particularly true if you have previously programmed in languages that do not have a REPL.
You will find that many examples in the Python documentation, online tutorials, manuals, and courses are copied and pasted from an interactive session while you are learning Python or exploring new features and concepts. This is something that you will notice while you are learning Python or exploring new features and concepts. You will be able to distinguish them due to the distinctive prompts that are shown by the REPL, which you will get familiar with in the section entitled Executing the Python Command.
Now that you have a foundational understanding of interpreters and REPLs, you are prepared to dive headfirst into the action. You are going to learn how to begin and conclude an interactive Python program in the next session.
session.
Starting and Ending REPL Interactive Sessions
Every Python installation has a copy of the standard REPL that Python ships with. Just launching the Python interpreter from the command line with the interactive switch turned on will allow you to start a new REPL or interactive session. When you switch to this mode, you will be placed in a shell environment that allows you to run Python code. Getting an understanding of how the input code operates is, in essence, a method of obtaining rapid feedback on it.
You are going to learn how to create a new Python interactive shell by using the python command and some of the arguments that are available on its command line in the following sections.
You will also get an understanding of the typical appearance and feel of a Python interactive shell, in addition to some of the fundamental characteristics and features of this kind of shell. At long last, you will discover how to put an end to a Python interactive.
session.
Running the
When you have downloaded and installed Python on your own computer, you will be able to begin making use of this remarkable technology straight away. Open a window for the command line and type the python command without the quotation marks to launch an interactive Python shell or session.
arguments:
$ python
Python will now be in its interactive mode once you run this command. The interpreter will execute, and the output that you obtain will have some resemblance to the following:
this:
>>>
Python 3.11.0 (main, Nov 6 2022, 13:27:29) ... on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
The very first line of this output provides details on the version of Python that you are now using as well as the operating system that the interpreter is being run on. The second line displays a message that includes commands that you may use to gain more information on Python in general.
The major prompt of a conventional Python interactive session or shell is shown on the output’s very last line, which has been highlighted for your convenience. This prompt consists of three greater-than signs (>>>), which are also referred to as chevrons. This is the default setting. It is meant to convey to the audience that the interpreter is prepared to take feedback at this time. Please take note that the normal Python REPL does not enable
syntax highlighting and highlighting. On the other hand, you’ll notice that the examples in this lesson are displayed with the assistance of a syntax highlighter. Remember this specific fact because, if you run the examples on your PC, you won’t see the syntax highlighted on the screen.
In addition to this primary prompt, the interpreter also has a secondary prompt that is represented by three dots ( … ). When you are attempting to input compound statements or line continuations, this prompt will show. Further information on this question will be provided to you in the Running Complex Statements and Handling With Explicit and Implicit Line Continuations sections.
sections.
Passing Command-Line Options to the
The python command may accept a wide variety of parameters from the command line. While working in a REPL session, you may find that a couple of these are helpful. The -i flag is considered to be one of the most important alternatives to consider in this scenario. Once a script is executed or a piece of code is executed with the -c option, this option causes the interpreter to enter the interactive mode. Note that the -c option for the command line enables you to rapidly execute a Python statement or expression that you give as a string on your computer’s command line. To understand how this option works, you may execute the command python -c “print(‘Hello, World!’)” on your computer.
You may use the -i option to check the current global variables in your script or to examine the stack trace in the event that your program throws an exception. Both of these operations are possible when the option is used.
To demonstrate how this choice may work for you, consider the following example:
script:
# sample.py
def read_data():
# Read data from a file or database...
return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sample = read_data()
def mean(data):
return sum(data) / len(data)
average = mean(sample)
This script takes a small amount of sample data from a file or database and then gives a function to calculate the mean, also known as the average, of the data.
Proceed to execute the script using the following parameters.
command:
$ python -i sample.py
This program executes the code found in sample.py as soon as you click Enter, and then it immediately brings you into an interactive session. This session will be easily identifiable by the fact that the major prompt of the REPL will be shown on your screen (>>>).
From now on, you will be able to examine, test, and debug the code that is included in sample.py as it runs.
needed:
>>>
>>> globals()
{
'__name__': '__main__',
...
'read_data': <function read_data at 0x104dd4860>,
'sample': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'mean': <function mean at 0x104fe3ec0>,
'average': 5.5
}
>>> mean([2, 3, 3, 2])
2.5
>>> mean([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../sample.py", line 10, in mean
return sum(data) / len(data)
~~~~~~~~~~^~~~~~~~~~~
ZeroDivisionError: division by zero
In the following demonstrations, you begin by using the built-in globals() function in order to investigate the global names that are specified in your script. This function will return a dictionary that has a mapping of names to the objects that correspond to those names. In the second example, the mean() function is called with a fresh data sample. Notice that when you execute a piece of code in an interactive session, you will often receive quick response in the form of an output on your screen. The output of the code will be immediately recognizable to you since it will not contain any kind of leading prompt.
The last example uses the mean() function, but passes an empty list as its input. Since executing len() with an empty list always results in 0, the method in question throws a ZeroDivisionError when it is used in this scenario. When using the -i command-line option with the Python command, it is important to bear in mind that the
PYTHONSTARTUP environment variable won’t be read. Further information on this environment variable is provided in the.
Including a folder labeled “Startup File.”
When you run Python in interactive mode, you should also think about using the -b flag as additional option on the command line. This option is helpful when you are running code that compares bytes objects and you want to get a warning if a string or integer value gets in the midst of a comparison.
comparison:
>>>
>>> # Run python with the -b option
>>> b = b"Hello"
>>> s = "Hello"
>>> b == s
<stdin>:1: BytesWarning: Comparison between bytes and string
False
Since the second example uses the -b option, the interpreter will show a warning if it discovers an action that compares bytes with string or integer values. If you choose not to make use of this option, there will be no warning shown.
shown:
>>>
>>> # Run python without the -b option
>>> b = b"Hello"
>>> s = "Hello"
>>> b == s
False
The comparison yields the same result as the one before it, which is False, due to the fact that the values are of different data types. But in this last example, you won’t receive any warnings that explain why you’re receiving this outcome, and you won’t be able to figure it out on your own.
While working with Python in interactive mode, you have access to a wide variety of choices; the ones listed below are only few examples. Check out Python Command-Line Arguments for an exhaustive rundown of all available arguments for the command line.
.
Exiting the Current Python REPL Session
If you’re accustomed to working on the command line or terminal, then you probably don’t appreciate having to constantly close and reopen terminal windows. Executing Command Line Interface (CLI) tools may be a regular part of your workflow. Whenever the job is complete, you may close the CLI tools and then return to the shell session you were previously working in.
Whenever you use Python in interactive mode, there is a possibility that this may occur. Since you are operating in a separate environment while you are within the REPL, you will not be able to execute regular shell commands after you have entered it. It is necessary to put an end to the REPL session before you may return to your regular shell.
Exiting an interactive session may be done in a number different ways. You are free to use one of the two Python programs listed below.
functions:
Python is equipped with both of these functions by default. Because of this, they are accessible to you at any time throughout a session that involves interaction. You are able to log out of the currently active session by automatically triggering a SystemExit exception using any of these routines.
You also have the option of manually raising the SystemExit exception with an exit code of 0. Doing so will have the same result. You won’t see any difference in the outcome, and the current REPL session will end as usual.
Using any one of these tools will allow you to exit the Python interactive session you are currently in and return you to the shell for the operating system (OS). After this is complete, you will be able to issue ordinary shell commands once again.
Use one of the following keyboard keys, which vary based on the operating system you are now using, to stop a REPL session as a further alternative.
system:
-
Ctrl
+
D
on Unix systems, such as Linux or macOS -
Ctrl
+
Z
and then
Enter
on Windows systems
In the respective operating system, the end-of-file character (also known as EOF) is represented by these key combinations. They make it possible for you to end the currently active interactive session since the interpreter runs in a unique file known as __main__. If you investigate the __name__ variable, you will see that this is really the case.
attribute:
>>>
>>> __name__
'__main__'
The __main__ file stores all of the Python code that is executed during an interactive session. This file continues to run until an EOF character is encountered. This indicates that once the interpreter comes across this character, it will instantly put an end to the currently running instance of REPL.
session.
Running Code in a REPL Session
You should now be familiar with the concept of a Python REPL and the reasons why Python programmers like using them. You have also gained the knowledge necessary to initiate a REPL session by using the python command and other parameters available for the command line. In addition, you have gained the knowledge necessary to end an interactive session in Python and return to the shell of the operating system.
In the next chapters, you will acquire the knowledge necessary to input and run Python code in an interactive environment.
session.
Evaluating Expressions and Simple Statements
You will be able to instantly begin inputting Python code and running it as soon as you have successfully opened an interactive session of Python from your command line. To do this, return to the window where you are entering commands and execute the python command.
Once the principal prompt for the REPL (>>>) displays on your screen, you should write in the following expressions and hit the Enter key after each one.
them:
>>>
>>> 5 - 2
3
>>> sum([1, 2, 3, 4])
10
>>> 42 > 7
True
>>> number = 42
>>> 7 / 0
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
The first phrase takes two integers as input and then shows the difference between them. The second expression is a call to the built-in sum() function, which accepts a list of values and returns the sum of those values. This function takes a list of items and returns the entire sum. In the third example, you put into action a Boolean expression that does a comparison between two integers.
The number variable is defined and initialized with the help of an assignment statement, which is shown in the fourth illustration. The Python interpreter does not produce any output on your screen since assignments do not return any value. Instead, it quickly returns to the initial prompt that was shown. The last example demonstrates how Python presents an error when there are problems with the code.
When you are running these examples, take notice of how the interpreter returns to the principal prompt (>>>) following the execution of each expression. This provides you with the opportunity to add a new expression. You should now have a better understanding of how the REPL cycle works. Your expressions have been read, evaluated, and their accompanying results have been printed by the Python interpreter, which has now completed the loop and returned to its primary.
prompt.
Running Compound Statements
By the use of the examples included in the part before this one, you have successfully carried out basic statements in a Python interactive session. These expressions are referred to as simple statements since there is no indentation in the code block that surrounds them.
Compound statements, such as conditionals, loops, and with statements, are all available in the Python programming language. Indented code blocks are required whenever a compound statement is used. A supplementary prompt is available in the Python interpreter, which allows you to input the code block for compound statements.
Have a look at the following illustration of a conditional sentence:
statement:
>>>
>>> number = -42
>>> if number < 0:
... print("negative")
... elif number > 0:
... print("positive")
... else:
... print("equal to 0")
...
negative
At the beginning of this piece of code, you are going to be defining a variable that will store a number. After that, you will initiate a statement with conditions.
After you have finished typing the colon letter (:) and have pressed the Enter key, you will see three dots (…) appear on your screen. The supplementary prompt for the REPL may be identified by these dots. The fact that you are being prompted to input the requisite indented blocks of your present compound statement is an indication that you can do so. Note: You have to hit Enter twice in order to exit the secondary prompt that the REPL presents you with. After taking this step, you will be brought back to the first prompt.
It is important to bear in mind that the default REPL does not allow entering indented code blocks while you are writing programs.
auto-indentation:
>>>
>>> if number < 0:
... print("negative")
File "<stdin>", line 2
print("negative")
^
IndentationError: expected an indented block after 'if' statement on line 1
With the Python standard REPL, you are required to manually supply the correct indentation for each indented code block that you need to input. If you don’t do it, you’ll receive an error called IndentationError, just as in the example.
above.
Dealing With Explicit and Implicit Line Continuations
When you have to make use of line continuations, the REPL’s secondary prompt occurs. Here is another scenario in which it arises. When many physical lines are joined together into a single logical line in an explicit manner using the backslash character (), this is known as a line continuation.
character:
>>>
>>> number = 42
>>> assert isinstance(number, int) and number > 0, \
... f"number greater than 0 expected, got: {number}"
...
This
The assert statement does two tests on the value of number. The first thing that it does is check using the built-in isinstance() function to see whether the value is a number that can be represented as an integer. After that, it determines whether or not the value being entered is larger than 0. In the event that one of these criteria is not met, the statement will generate an AssertionError and pass the message that was given to it as the argument.
Line continuations may also occur when you construct a list, tuple, or dictionary by using many lines to write an expression that is bounded by a pair of brackets. For example, when you define a list, tuple, or dictionary.
:
>>>
>>> fruits = [
... "apple",
... "banana",
... "orange",
... "grape",
... "lemon",
... ]
>>> inventory = {
... "mouse": 120,
... "keyboard": 50,
... "laptop": 200,
... "headphones": 240,
... }
When you hit Enter after opening a bracket in the REPL, such as [] or () or, you are presented with the REPL’s secondary prompt. The merging of lines in this manner is referred to as implicit line joining.
You may also utilize implicit line joining in other circumstances, such as expressions involving mathematics and booleans, function definitions and calls, list comprehensions, and generator expressions. In a nutshell, implicit line continuation will be present in all of the Python constructs that allow for the use of brackets of any kind, such as [], (), or.
.
Printing vs Evaluating
When you run Python in interactive mode, you’ll notice that the interpreter instantly shows the result value of evaluating or executing any expression or statement. You can see this for yourself by observing the output of the interpreter. This holds true for each and every statement and expression that is capable of producing a return value.
Statements that do not provide return values are not interpreted and so do not produce any output from the interpreter. You are well aware that this is the case with assignment statements.
This is how the Python interpreter acts since its main purpose is to provide you rapid feedback on how the functionality of your code is working. Because of this behavior, utilizing the built-in print() method becomes almost pointless if you are working in an interactive environment.
In REPL sessions, however, there is at least one situation when the print() function is useful. When you wish to show the result of an expression or statement that may either return None or will always return None, you need to use the print() function.
For instance, one of the most typical mistakes that Python novices make when they first begin to learn about lists is that they anticipate receiving new lists in response to their calls to various list methods. These list methods include.append(),.sort(), and the like.
like:
>>>
>>> numbers = [2, 4, 1, 3]
>>> numbers.sort()
>>> numbers.append(5)
It may seem as if these method calls did not carry out any significant activity since they do not provide any output that is shown on the screen. Yet, they did it.
The majority of list methods carry out the transformation or calculation they were designed to do locally. In other words, list methods often alter the object that is used as the foundation for the list rather than producing a new one. Because of this, the majority of list methods return None, which the REPL automatically ignores when it is encountered. As a direct consequence of this, you will not see anything on your screen.
You have to use the print command in a REPL session if there is ever a time when you need to show the value None ()
function:
>>>
>>> print(numbers.append(6))
None
>>> numbers
[1, 2, 3, 4, 5, 6]
>>> value = None
>>> value
>>> print(value)
None
You are using the print() function in this piece of code to display the return result of the.append() method, which, as you can see, is None.
It is important to keep in mind that you can always retrieve the value stored in a particular variable by entering the name of the variable and then hitting Enter after it, just like you did with the numbers. On the other hand, if the variable is presently set to None, then there won’t be anything shown on your screen. You’ll need to make use of the print() function, just as you did with value.
.
Flagging and Understanding Errors
The interpreter will automatically output the appropriate error message and traceback if an error occurs during a REPL session. After that, it navigates back to the principal prompt of the REPL. This pattern of conduct will be shown in the following examples:
action:
>>>
>>> greeting = "Hello, World!
File "<stdin>", line 1
greeting = "Hello, World!
^
SyntaxError: unterminated string literal (detected at line 1)
>>> 42 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> sum()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() takes at least 1 positional argument (0 given)
In the first example, the string literal is not correctly terminated with a double quotation as is required ( ” ). This results in a SyntaxError being thrown. In the second example, you are attempting to divide 42 by zero, which causes a ZeroDivisionError exception to be thrown. In the last example, you make a call to the built-in sum() method without passing it any parameters, which results in a TypeError being generated.
All of these mistakes are shown on the screen as soon as they are found. This behavior gives you the ability to quickly and thoroughly analyze the error message as well as the traceback in order to locate the underlying problem and correct it.
code.
Using the
When you execute a statement that returns a value, the interpreter saves that value in a special variable whose name begins with a single underscore character (_), and it does this each and every time. This variable may be accessed and used in exactly the same way as any other variable in Python.
The following are a few of examples that demonstrate how the implicit variable may be put to use when you are working with.
expressions:
>>>
>>> 42 < 7
False
>>> _
False
>>> 12 + 30
42
>>> _
42
Expressions are being evaluated by you as part of these exercises. Every time an expression is evaluated, a return value is obtained and placed in the variable by default. This value can never be changed.
When it comes to function calls, will save the value that is returned by the target function if it is not None. If the function returns a value other than None, then will not keep that value. If, on the other hand, the function returns Nothing, then the variable will continue to have the value of whatever came before it.
operation:
>>>
>>> pow(4, 2)
16
>>> _
16
>>> print("Hello, World!")
Hello, World!
>>> _
16
The result of calculating a number’s power according to an exponent that you provide is returned by the built-in pow() function. Since the function’s actual output is not identical to the value None, the variable is automatically given a new value. If, on the other hand, you make a call to a function that does not return anything—for example, print()—then the variable will not be altered.
You can see how to establish a counter and initialize it in the example that follows by making use of an assignment statement.
variable:
>>>
>>> counter = 0
>>> _
16
>>> counter
0
>>> _
0
There is no value that is returned by assignments. They instead save a reference to a value in a variable that they may later access. Once the statement is executed in this scenario, the variable is not given a new value. Because of this, the value 16 is still stored in the variable even if it was used in earlier cases.
Take note that the value referenced by a variable will be returned whenever you access that variable during an interactive session. In this particular instance, the value is also given to the variable to be stored.
You may use the variable in expressions and calculations since it is a standard Python variable.
statements:
>>>
>>> numbers = [1, 2, 3, 4]
>>> len(numbers)
4
>>> sum(numbers) / _
2.5
In this illustration, the first thing that you do is build a list of values. The next step is to use the len() function in order to get the total number of values included in the list. Python will save this value in the variable without your intervention. In the last step, you will calculate the mean of your list of values by using the symbol.
It is important to bear in mind that the variable will only be available for use in an interactive REPL session while you are working with this variable. You won’t encounter this implicit if you execute your code in script mode, since it will be hidden from you.
behavior.
Reloading Imported Modules
Let’s say that you’re working on one of your projects and need to write a Python module that has a few functions. Simultaneously, you are putting the code of the module through its paces using Python’s interactive debugger to see its behavior in real time. Take for instance the fact that you have the following:
module:
# greeting.py
def greet(name="World"):
print(f"Hello, {name}!")
You will need to create a welcome() method in this file so that a welcoming message may be shown on the screen. Instructions for loading and executing this code in a REPL are provided below.
session:
>>>
>>> import greeting
>>> greeting.greet()
'Hello, World!'
>>> greeting.greet("Pythonista")
'Hello, Pythonista!'
Consider for a moment that you have the desire to include a new parameter into your function. The welcome message may be printed using all capital letters if the parameter is a Boolean flag that specifies this behavior. In order to do this, you will need to alter the function such that it looks something like.
this:
# greeting.py
def greet(name="World", upper=False):
greeting = f"Hello, {name}!"
if upper:
greeting = greeting.upper()
print(greeting)
Because of this upgrade, you are now able to use welcome() with an upper parameter. If you set the argument to True, then the message that is shown will have all of the letters in the message capitalized. You are excited to test out your modifications in the REPL session you are now using. Thus, you import the module once again in the hopes of running the updated version of greet().
follows:
>>>
>>> import greeting
>>> greeting.greet("Pythonista", upper=True)
Traceback (most recent call last):
File "<input>", line 1, in <module>
greeting.greet("Pythonista", upper=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: greet() got an unexpected keyword argument 'upper'
What? Do you find yourself in an unanticipated argument? When making a change to anything in the greeting.py file, executing the import again does not cause the module to be reloaded since doing so would be inefficient. When you execute the import again, Python will not load the previously imported modules again.
If you wish to get around this behavior without having to close down your current REPL session and start a new one, you may utilize the reload() method that is provided by the importlib library.
:
>>>
>>> import importlib
>>> importlib.reload(greeting)
<module 'greeting' from '.../greeting.py'>
>>> greeting.greet("Pythonista", upper=True)
HELLO, PYTHONISTA!
Your function should now be working! The updated version of your welcome module has been loaded successfully thanks to the reload() method that you used. This tip might be helpful anytime you’re working in a module on your code editor and evaluating your changes in a session of the REPL.
Now that you are familiar with the fundamentals of using a Python interactive shell to input and run code, it is time to investigate and get familiar with a few editing tools that are not available in the default REPL.
provides.
Editing Code in the Standard REPL
While operating in interactive mode, the majority of Python interpreter versions have capability for editing source code. These editing tools include rudimentary code completion and a history of the code being edited. If you often work on Unix-like systems like Linux and macOS, then you may already be acquainted with some of these functions, which are available in both the Bash and Korn shells. These features can be found in both shells.
These editing tools are made possible by the use of the GNU Readline library, which provides support for a variety of helpful editing formats. Note: If you want to verify whether or not you have access to code editing capabilities in your current configuration, you may do so quickly by pressing Ctrl + P at the prompt of the REPL. The most recent code instruction in your history ought to be shown by using this shortcut. If nothing occurs or the character P shows on the screen, this indicates that the facilities for editing code are not accessible. Other from that, you should be good to go!
You’re going to learn how to utilize code history and code completion in a Python interactive session while you’re using the standard Python environment in the following sections.
REPL.
Code History
While you are working in interactive mode, the default REPL will save a full history of all of the code that you have written and ran during that time. This history is normally stored in a file known as.python history, which is kept in the directory that is associated with your user account.
You have the ability to go through this history while you are in the interactive mode by using the arrow keys on your keyboard. You may go farther back in time by using the Up key. You are able to go ahead in time while using Down.
After you have located the required line of code, you may confirm your selection by using the Enter key, and then you can reuse the target instruction:
Take note of the way in which the code in the history of your REPL instantly becomes accessible for reuse. You may traverse the history of the code by using the Up and Down keys until you locate the snippet you are looking for.
The navigation begins at the very bottom of the history file and works its way to the top. When you hit the Up key, you will go back one line in your history to the line before the one you were on.
When you have located the line of code that you want to reuse or edit, you may accept it by pressing the Enter key. Keep in mind that the indentation of each line in your code history will remain the same as it was when you wrote the code for the very first time, which will both save you time and be handy.
time.
Code Completion
Standard REPLs are equipped with rudimentary completion features that may be used for variable, object, and module names. When you begin an interactive session, this feature will have its status changed to “activated” immediately. When you start typing the first characters of a given name and then hit the Tab key, the code completions for that name will be shown for you to choose from. The search for the completion is started by this step.
In the event that the search turns up a suitable match, your name will be pre-filled for you instantly. If the search returns more than one result, you will need to press Tab once more in order to see the full list of names that are relevant to the search. If you hit Tab again and nothing displays, it means that your search was unsuccessful and no results were found.
While carrying out its operations, the code completion system considers the following objects:
search:
-
Python
keywords
-
Built-in
function
,
class
, and
object
names -
Currently defined names, such as
variables
,
functions
, and
classes
-
Imported
module
and
package
names
Here is an illustration of how the code completion mechanism in the REPL really works in practice:
If the REPL detects a unique match while you are inputting the first character or characters of your target name and pressing Enter, you will get an automated completion of the target name. When the completion system discovers more than one name that is a match for your search, you will need to press Tab once more in order to retrieve the list of names that are a match.
You have the option of typing a few more letters and then pressing Tab once again, or you may just input the name or keyword in its entirety.
When it comes to accessing attributes using dot notation, such as in obj.attr, the code completion system will recommend completions from the target object’s attributes and methods. These completions are as follows:
You may rapidly view the list of methods and attributes that are associated with an object by typing the name of the object, followed by a period, and then pressing the Tab key. After that, you may begin entering the name of the method or attribute you want to target, and when you are finished, hit Tab once again to finish.
The default REPL only offers a rudimentary selection of code editing tools. Yet, when you need to utilize an interactive session but don’t have a more powerful REPL, they may be really handy. These features of code editing software have the potential to boost your productivity and make your time spent coding more enjoyable.
pleasant.
Useful Keyboard Shortcuts
While you’re working in a REPL session, learning certain helpful keyboard shortcuts may greatly increase the amount of work you get done in a given amount of time. When you hit Ctrl + C on the main or secondary prompt of the REPL, for instance, the input is canceled and you are brought back to the primary prompt.
prompt:
>>>
>>> print(
KeyboardInterrupt
>>> if True:
...
KeyboardInterrupt
If you hit Ctrl + C on either the main or secondary prompt, the interpreter will throw a KeyboardInterrupt exception and will then go back to the primary prompt.
When you hit Ctrl + C while some section of code is executing, the interpreter will throw a KeyboardInterrupt exception. This will cause the code’s execution to be terminated, and you will be brought back to the main prompt.
This latter feature is handy when you initiate a long-running operation that you are not willing to finish or when you mistakenly get into an endless loop. [Case in point:] [Case in point:]
:
>>>
>>> while True:
... print("Hello!")
...
Hello!
Hello!
Hello!
^CTraceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
Hello!
This example shows a while loop that continues on forever. You may exit the loop by hitting the Control key together with the letter C on your keyboard. Once you press these keys in succession, the main prompt will appear once again, and your REPL session will be prepared to accept additional input at this point.
The default REPL offers a plethora of additional keyboard shortcuts that are both intriguing and helpful. The following table provides examples of
them:
Keyboard Shortcut | Description |
---|---|
Ctrl + L |
Clears the screen, reprinting the current line at the top |
Ctrl + D |
Exits the current REPL session |
Ctrl + C |
Raises a
exception and loops back to the primary prompt |
Ctrl + B |
Moves the cursor back one character |
Ctrl + F |
Moves the cursor forward one character |
Del or Backspace |
Deletes the character to the right or left of the cursor, respectively |
Ctrl + D |
Deletes the character underneath the cursor |
Ctrl + A |
Moves the cursor to the start of the line |
Ctrl + E |
Moves the cursor to the end of the line |
Ctrl + K |
Kills, or deletes, the text from the current cursor position to the end of the line |
Ctrl + W |
Kills from the cursor to the previous whitespace |
If you want to become more skilled at entering and modifying code during an interactive session, familiarizing yourself with these shortcuts on the keyboard can assist. The official documentation for the GNU Readline software contains a selection of additional keyboard shortcuts.
library.
Getting Help and Introspecting Code in the REPL
The ability to obtain prompt assistance and direction regarding the proper utilization of the programming language, libraries, and tools that you are working with is an essential component of any environment for writing code, such as an integrated development environment (IDE), an editor, or a read-eval-print loop (REPL).
If you are using the normal REPL, then you will have access to a few tools that, depending on your requirements and the nature of your program, will enable you to obtain assistance and inspect your code.
context.
Using Python’s Built-in Help System
The built-in help() method provides access to the built-in help system that is included with Python. You are able to make use of this function by invoking it in two different contexts.
ways:
-
With an
object
or a
string
as an argument, which gives you access to the object’s help page -
With
no arguments
, which enters Python’s help system
The information that may be found in an object’s docstrings is often included on the help page associated with the item. In addition to that, it could have a list of methods and characteristics. For instance, the following is a portion of the page for the str class that can be accessed by entering help(str) into your REPL.
session:
>>>
>>> help(str)
Help on class str in module builtins:
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
...
In this demonstration, the str class object is sent along as a parameter to the help() function. You may view the support page for the class in this manner. You may navigate the page by using the Up and Down buttons on your keyboard. After you have finished obtaining the information you want, you may quit the help viewer by pressing the Q key.
If you provide a string to the help() function as an argument, the help system searches for it as the name of a module, function, class, method, keyword, or documentation subject. If it is found, the help system displays that information. The appropriate section of the help file is shown on the screen. When the object you’re trying to access isn’t present in the namespace you’re working in, you may use this approach to use the help() function.
Take, for instance, the scenario in which you need assistance with the pathlib module but have not yet imported it into your project. After that, you may call the function help() with the parameter “pathlib” in front of it. You’ll receive something like the
following:
>>>
>>> help("pathlib")
Help on module pathlib:
NAME
pathlib
MODULE REFERENCE
https://docs.python.org/3.11/library/pathlib.html
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
...
When “pathlib” is passed as an input to the help() function, the help page for the module is shown. Notice that if you use help() with the pathlib name as an argument, you will receive a NameError since you haven’t imported the module to your current namespace yet. This is because you are using an older version of the pathlib library.
The second method for using the help() function is to just call the function without passing any parameters. You may access the built-in assistance in this manner.
system:
>>>
>>> help()
With this call, you will be able to access the help mode. When you first run it, you’ll see that the prompt has changed from >>> to help> very soon after you do so. This new prompt will serve as a gentle reminder that you are now operating in the interactive assistance mode.
You are able to insert keywords, module names, function names, or any other name while you are in the assistance mode. The documentation page relevant to the target will be shown when the assistance system has finished its search for that term. At the help> box, type sys, then hit the Enter key to test out the usefulness of this feature. You should see the following page when you access your account.
screen:
>>>
help> sys
Help on built-in module sys:
NAME
sys
MODULE REFERENCE
https://docs.python.org/3.11/library/sys.html
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
...
You may leave this page by using the Q key on your keyboard, as I’ve said before. You have the ability to look for a variety of subjects using the help system. Just choose the relevant subject, then hit the Enter key. If the issue in question has an accompanying documentation page, then you will see that page displayed on your screen. In such case, you will get an ImportError, which will take you back to the original screen.
prompt:
>>>
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
help> iterable
Traceback (most recent call last):
...
ImportError: No Python documentation found for 'iterable'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.
In this example, you start by doing a search for the phrase keywords. This search discovers the page on Python keywords, and it displays it to you. After that, you look for references to the phrase “iterable.” Since this particular subject does not have a documentation page, you will get an ImportError, which will exit you from the assistance system.
When you have located the information you desire, you will be able to leave the assistance system by first entering q, which stands for quit, and then hitting Enter. You’ll end up back at your REPL if you do it this way.
session.
Introspecting Your Code Dynamically
When you’re working in a REPL session, you have direct access to some cool Python built-in tools that you can use to inspect your code and obtain more information and context on the objects that you’re working with. You can use these tools to do things like introspect your code or investigate the context of the objects you’re working with.
Included among these built-in tools are the and the.
following:
Function | Description |
---|---|
|
Returns the list of names in the current local scope when you call it with no argument. Attempts to return a list of valid attributes for the object passed as an argument. |
|
Returns the
attribute for a module, class, instance, or any other object with this attribute. The
attribute holds a list of names pertaining to the underlying object. |
|
Returns a dictionary representing the names in the current local scope. |
|
Returns the dictionary representing the current module namespace. |
|
Returns the type of an object when you call it with one argument. |
You may inspect your code and extract helpful information that you can then use to the process of coding by using any one of these built-in functions. You can utilize this information afterwards.
Take for instance the scenario in which you are dealing with dictionaries and want to compile a list of all the methods and properties that are included inside this class. You may do something along these lines:
this:
>>>
>>> dir(dict)
['__class__', ..., 'popitem', 'setdefault', 'update', 'values']
The example’s output consists of a string representation of a list of the names. This list will include all of the dict class’s properties and methods that have been specified. This built-in function may be used with any Python object you want.
The vars() method performs operations that are similar to those of the dir() function, except it produces a dictionary of name-object pair rather than a list.
When you wish to find out which names are declared in a certain scope inside your code, you may also find that the locals() and globals() functions come in handy. In conclusion, the type() method assists you in determining the data type or class of a certain object inside your program.
code.
Customizing the Standard REPL
In interactive mode, the Python interpreter provides you with the ability to modify a selection of its behaviors and features. A so-called startup file is a Python file that the interpreter reads and runs when you begin an interactive session. This allows you to personalize your REPL by reading and executing your own code.
You may also use the Rich third-party library to modify the output of any code that you run in a REPL session. This option is available to you if you execute the code in one of those environments.
In the following sections, you will learn the fundamentals of how to utilize these tools in order to improve the quality of your user experience while maintaining the normal Python environment.
REPL.
Providing a Startup File
The default REPL will allow you to provide a startup file, which you can then use to customize some of the existing capabilities or add new features to your interactive sessions. Only interactive sessions will trigger the execution of this file. When you attempt to start a program using the python command, it does not run successfully. So, you won’t need to worry about essential applications being damaged in any way.
Any Python code at all might be included in the starting file. When interactive mode is being used, this code will be executed before the first prompt is presented.
It is essential to call attention to the fact that the startup file executes in the same namespace as the interactive code that you will be executing later. So, the objects that are declared or imported in this file will be accessible to you throughout your interactive session. When you wish to load tools and adjust the features of your interactive shell, this behavior is helpful since it allows you to do both.
Before you can do any great stuff with a startup file, you need to understand how to tell the interpreter which file you want to use as your startup file. This is necessary before you can perform some of the interesting things that can be done with a startup file. You may do this by modifying the PYTHONSTARTUP environment variable that is stored in the shell of your operating system.
If you are using Linux or macOS, you may go to the home folder on your computer and access the configuration file for your shell there. After you have that file open, add the following line at the very end of it:
it:
# .bashrc
# ...
export PYTHONSTARTUP=~/.pythonstartup
# .zshrc
# ...
export PYTHONSTARTUP=~/.pythonstartup
When you launch a terminal or command-line window in Linux or macOS, the shells of these operating systems automatically load the configuration file that corresponds to them. By doing so, you can guarantee that the PYTHONSTARTUP variable will constantly be accessible on your system.
In this example, you are going to set the PYTHONSTARTUP variable to point to the location of your desired startup file, which is located at /.pythonstartup. In this scenario, the file will be located in the home directory that you have access to, and its name will be.pythonstartup.
Take note that the name of the file doesn’t really matter. You are free to give it any moniker you like. Additionally, you are free to place the file in any directory of your choosing. Make sure that the PYTHONSTARTUP environment variable in your computer contains the correct path to the file.
Check out the section titled “Configuring Environment Variables” in the “Your Python Coding Environment on Windows: Setup Guide” for a comprehensive guide to the process of creating system variables if you are using Windows as your operating system. After following the instructions, you will need to populate the PYTHONSTARTUP system variable with a path that is appropriate.
After you have changed the value of the PYTHONSTARTUP variable, proceed to create the file in the folder of your choice. Launch the text editor of your choice, open the file, and get ready to add some code. In order to get things rolling with your individualized startup file, you will begin by adding some
imports:
# .pythonstartup
from importlib import reload
from pprint import pp
You are aware that the reload() function enables you to reload modules after making changes to their content, which enables you to test whether or not the modifications were successful. It would be wonderful if you could make this function accessible at all times during your interactive sessions. It will save you time and prevent you from having to perform work that is repetitive.
You are able to print pretty-formatted versions of data structures like lists and dictionaries by using the pp() function, which is contained within the pprint module.
In order to test out these brand new features, you will need to initiate the opening of a fresh command-line window or terminal. The next step is to run Python in an interactive session. When you get there, carry out the following.
code:
>>>
>>> pp(globals())
{'__name__': '__main__',
...
'__builtins__': <module 'builtins' (built-in)>,
'reload': <function reload at 0x101455c60>,
'pp': <function pp at 0x1014f3380>}
Cool! It is possible to make use of the pp() function right away. Take note that reload() also appears as an entry in the global namespace that you are currently using.
You are free to include any imports that you require in the startup file for your REPL. When you are running an interactive session, this is a nice and speedy way to ensure that you have useful tools available to you at all times.
You can change the characters that are used to identify the primary (>>>) and secondary (…) prompts by editing the startup file for your REPL, which is yet another interesting customization option. Altering the values of the sys.ps1 and sys.ps2 variables will allow you to accomplish this goal.
Feel free to incorporate the following code into your new venture.
file:
# .pythonstartup
import sys
from importlib import reload
from pprint import pp
sys.ps1 = "py$ "
sys.ps2 = "py> "
You are instructing the interpreter to use the “py$” prompt as the primary prompt and the “py>” prompt as the secondary prompt in this instance. Start a brand new session of the REPL to test out this updated look and feel. The exterior of your shell will resemble the following:
this:
>>>
py$ numbers = [
py> 1,
py> 2,
py> 3,
py> ]
py$
Changing the prompts that are displayed on the REPL is possibly an interesting trick to investigate. In practice, however, using different prompts could cause other Python developers who are looking at your screen to become confused. Therefore, it is in your best interest to stick to the standard prompts.
There are a ton of other fun and useful modifications and customizations that you can incorporate into your REPL’s startup file. Don’t be so reticent! When you are working in an interactive environment, don’t be afraid to try new things in order to improve both your user experience and your productivity.
mode.
Colorizing REPL Output With Rich
You will be able to use rich text and pretty formatting in the terminal if you utilize the Rich library. The highlight of the pretty printing was included in Rich 5.1.0. You are able to colorize the output of the standard REPL by utilizing this feature. However, before you can use Rich, you will first need to install it using the pip command from the Python Package Index (PyPI), as shown below.
command:
$ python -m pip install rich
After you have executed this command, you will then be able to colorize the output of your REPL session. Detailed instructions on how to complete the task can be found here.
session:
>>>
>>> from rich import pretty, traceback
>>> pretty.install()
>>> traceback.install(show_locals=False)
From this point forward, any output that you receive during the current REPL session will be formatted and colored according to the following specifications:
Take note that this newly gained capability is only here on a temporary basis. Only the interactive session in which you ran the code above is affected by this restriction. Utilize your startup if you would like this feature to be accessible in each and every section.
file:
# .pythonstartup
import sys
from importlib import reload
from pprint import pp
try:
from rich import pretty, traceback
except ModuleNotFoundError:
pass
else:
pretty.install()
traceback.install(show_locals=False)
# ...
By making this modification to the startup file for your REPL, you will be able to reproduce the behavior of output colorizing and formatting across all of the interactive sessions that have access to the Rich library. If Rich isn’t readily accessible in the instance of Python in which you’re working, the try…except…else blocks ensure that your startup file won’t generate an error message.
using.
Uncovering Missing Features in the Standard REPL
When compared to a code editor, integrated development environment (IDE), or full-featured REPL, the standard REPL is relatively basic and does not offer a large number of features that can assist you in coding or make you more productive. The presence of IDLE, which provides a feature-rich REPL and is included in the standard Python installation, is likely to blame for this lack of features. IDLE is included in the standard Python installation.
The following is a list of IDE-like features that the default REPL does not have. This list is not exhaustive.
support:
-
Automatic
indentation
-
Syntax highlighting
-
Contextual code or
command history
-
Bracket matching
-
Rich
code completion
and code suggestions -
Dynamic code and
type introspection
-
Session sharing
capabilities - Dynamic help, source code, and documentation access
You can test out your code and get immediate feedback by using the regular REPL, which is a fantastic tool that you can use. When you don’t have access to more sophisticated tools, it might come in handy to have something like this. Having said that, you must be aware of the constraints imposed by it.
When working with Python, having a REPL session that gives you access to all of the features described in the previous sentence would make the user experience better for you. They would make you more productive while simultaneously lowering the number of mistakes and typos that you would make in the code that you write.
To our good fortune, the capabilities of the Python standard shell can readily be extended and altered. As a result, there are a few alternative REPLs that implement the majority of the aforementioned features as well as additional ones. In the following section, you will acquire knowledge regarding several different REPLs that are available for.
Python.
Using an Alternative REPL
As a Python programmer, you will spend the majority of your time writing code in the interactive mode because it is an excellent instrument for validating hypotheses, demonstrating concepts, and troubleshooting programs. When you spend a significant portion of your time working with a given tool, you hope that it will provide you with a high-quality user experience along with a comprehensive feature set that will make your life easier and more pleasurable.
IDLE, which is included in the CPython implementation, is an improved replacement for the REPL that is provided by default. You don’t need to install anything from a third-party source in order to use IDLE, which makes it a very convenient tool.
However, there are other feature-rich REPLs available within the Python ecosystem to choose from. IPython, for instance, has been in existence for a considerable amount of time. This REPL offers a wide variety of features, including code completion, object exploration, sophisticated history management, and many more. Within the ecosystem of data science, this tool enjoys a lot of popularity.
bpython is another enhanced REPL that offers several features similar to those of an integrated development environment (IDE). These features will significantly improve the quality of your user experience and the amount of work you get done.
The python REPL is an additional option that is comparable in quality to the default one. It includes a variety of features such as syntax highlighting, mouse support, auto-completion, and multiline editing, among other things.
There are several choices available to you if you would rather use an online REPL instead.
available:
Online REPL | Description |
---|---|
Python.org shell |
An online interface for the standard REPL, available on the official Python website |
Replit |
An online coding platform that, among other features, allows you to start and use a Python REPL |
Python Morsels REPL |
An online Python REPL that allows you to copy or save your coding session |
If you do your own research on the Internet, you’ll find that there are a few other online Python REPLs, each of which has a unique set of features. Give each of them a try, and then select the instrument that responds most effectively to your requirements. Then, please share your experiences with the rest of the programmers below in the comments section.