by Leodanis Pozo Ramos Publication date Nov 12, 2025 Reading time estimate 57m intermediate tools
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Getting the Most Out of the Python Standard REPL
The Python standard REPL (Read-Eval-Print Loop) lets you run code interactively, test ideas, and get instant feedback. You start it by running the python command, which opens an interactive shell included in every Python installation.
In this tutorial, you’ll learn how to use the Python REPL to execute code, edit and navigate code h…
by Leodanis Pozo Ramos Publication date Nov 12, 2025 Reading time estimate 57m intermediate tools
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Getting the Most Out of the Python Standard REPL
The Python standard REPL (Read-Eval-Print Loop) lets you run code interactively, test ideas, and get instant feedback. You start it by running the python command, which opens an interactive shell included in every Python installation.
In this tutorial, you’ll learn how to use the Python REPL to execute code, edit and navigate code history, introspect objects, and customize the REPL for a smoother coding workflow.
By the end of this tutorial, you’ll understand that:
- You can enter and run simple or compound statements in a REPL session.
- The implicit
_variable stores the result of the last evaluated expression and can be reused in later expressions. - You can reload modules dynamically with
importlib.reload()to test updates without restarting the REPL. - The modern Python REPL supports auto-indentation, history navigation, syntax highlighting, quick commands, and autocompletion, which improves your user experience.
- You can customize the REPL with a startup file, color themes, and third-party libraries like Rich for a better experience.
With these skills, you can move beyond just running short code snippets and start using the Python REPL as a flexible environment for testing, debugging, and exploring new ideas.
** Take the Quiz:** Test your knowledge with our interactive “The Python Standard REPL: Try Out Code and Ideas Quickly” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
The Python Standard REPL: Try Out Code and Ideas Quickly
Test your understanding of the Python standard REPL. The Python REPL allows you to run Python code interactively, which is useful for testing new ideas, exploring libraries, refactoring and debugging code, and trying out examples.
Getting to Know the Python Standard REPL
In computer programming, you’ll find two kinds of programming languages: compiled and interpreted languages. Compiled languages like C and C++ have an associated compiler program that converts the language’s code into machine code.
This machine code is typically saved in an executable file. Once you have an executable, you can run your program on any compatible computer system without needing the compiler or the source code.
In contrast, interpreted languages like Python need an interpreter program. This means that you need to have a Python interpreter installed on your computer to run Python code. Some may consider this characteristic a drawback because it can make your code distribution process much more difficult.
However, in Python, having an interpreter offers one significant advantage that comes in handy during your development and testing process. The Python interpreter allows for what’s known as an interactive Read-Eval-Print Loop (REPL), or shell, which reads a piece of code, evaluates it, and then prints the result to the console in a loop.
The Python REPL is a built-in interactive coding playground that you can start by typing python in your terminal. Once in a REPL session, you can run Python code:
In the REPL, you can use Python as a calculator, but also try any Python code you can think of, and much more! Jump to starting and terminating REPL interactive sessions if you want to get your hands dirty right away, or keep reading to gather more background context first.
The Python interpreter can execute Python code in two modes:
- Script, or program
- Interactive, or REPL
In script mode, you use the interpreter to run a source file—typically a .py file—as an executable program. In this case, Python loads the file’s content and runs the code line by line, following the script or program’s execution flow.
Alternatively, interactive mode is when you launch the interpreter using the python command and use it as a platform to run code that you type in directly.
In this tutorial, you’ll learn how to use the Python standard REPL to run code interactively, which allows you to try ideas and test concepts when using and learning Python. Are you ready to take a closer look at the Python REPL? Keep reading!
What Is Python’s Interactive Shell or REPL?
When you run the Python interpreter in interactive mode, you open an interactive shell, also known as an interactive session. In this shell, your keyboard is the input source, and your screen is the output destination.
Here’s how the REPL works: it takes input consisting of Python code, which the interpreter parses and evaluates. Next, the interpreter displays the result on your screen, and the process starts again as a loop.
So, Python’s REPL is an interactive way to talk to your computer using the Python language. It’s like a live chat. The whole process is known as a REPL because it goes through four steps that run 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 powerful tool that you’ll wind up needing in your Python coding adventure, especially when you’re learning the language or when you’re in the early stages of a development process. That’s because the REPL offers several benefits, which you’ll learn about next.
Why Use a Python REPL?
As a Python programmer, you may spend considerable time in interactive mode. This mode provides a quick way to try out ideas and code snippets. In a REPL session, you can do some or all of the following tasks:
- Explore and learn Python syntax
- Try out and prove ideas, concepts, and implementations
- Quickly evaluate if your code snippets work
- 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
- Debug code snippets
- Explore standard-library and third-party modules, libraries, and APIs
- Inspect the implementation of classes, functions, and other objects
Clearly, as a Python developer, you’ll have many reasons to spend a lot of time in REPL sessions, working interactively with the interpreter. The most relevant benefit of using a REPL session is getting immediate feedback on how your code works.
Interactive mode is one of the best features of Python. It allows you to test solutions and experiment with the language in real time. If you want to know how something works, then just try it in an interactive shell.
You should definitely consider the interactive shell a powerful learning tool, especially if your previous programming experience has been with compiled languages that don’t provide a REPL.
While learning Python or exploring new features and concepts, you’ll notice that many examples in the Python documentation, online tutorials, manuals, and courses are copied and pasted from an interactive session. You’ll recognize them because of the REPL’s characteristic prompts, which you’ll get to know in the Running the python Command section.
With this introduction to interpreters and REPLs, you’re ready to get into action. In the following section, you’ll learn how to start and terminate a Python interactive session.
Starting and Terminating REPL Interactive Sessions
The Python standard REPL is available in every Python installation. To start a new REPL or interactive session, you just need to run the Python interpreter in interactive mode from your command line. This mode will present you with a shell environment where you can introduce and execute Python code.
In the following sections, you’ll learn how to start a new Python interactive shell using the python command and some of its command-line options.
You’ll also learn about the standard look and feel of a Python interactive shell, along with some of its core characteristics and features. Finally, you’ll learn how to terminate a Python interactive session.
Running the python Command
Once you’ve installed Python on your computer, you can immediately begin using the REPL. To start a Python interactive session, open a command-line window and run the python command without arguments:
This command makes Python enter its interactive mode. The interpreter will run, and you’ll get an output that looks something like this:
The first line of this output shows information about your current Python version and the platform on which you’re running the interpreter. The second line shows a message with commands that you can run to get additional information about Python in general.
The last line, which is highlighted in the output, shows the primary prompt of the standard Python REPL. By default, this prompt consists of three greater-than signs (>>>), also known as chevrons. Its purpose is to communicate that the interpreter is ready to accept input.
The interpreter also has a secondary prompt represented by three dots (...). This prompt appears when you’re entering compound statements or line continuations. You’ll learn more about this prompt in the Running Compound Statements and Dealing With Explicit and Implicit Line Continuations sections.
Passing Command-Line Options to the python Command
The python command can take several command-line options. Some of these can be especially useful when working in a REPL session. One of the most relevant options in this context is the -i flag. This option causes the interpreter to enter interactive mode after running a script or executing a piece of code using the -c option.
You can use the -i option to check the current global variables in your script or to inspect the stack trace when your program raises an exception.
To try this option out, say that you have the following sample script:
This script reads sample data from a hypothetical file or database and provides a function to calculate the mean or average of the data.
Go ahead and run the script with the following command:
Once you press Enter, this command runs the code in sample.py and takes you directly to an interactive session. You’ll recognize this session because your screen will present the REPL’s primary prompt (>>>).
From this point on, you can inspect, test, and debug the code in sample.py as needed:
In these examples, you first call the built-in globals() function to inspect the global names defined in your script. This function returns a dictionary that maps names to their corresponding objects. The second example calls mean() with a new sample of data.
The final example calls mean() with an empty list as an argument. In this case, the function fails with a ZeroDivisionError because calling len() with an empty list returns 0.
The -b flag is another command-line option to consider when you run Python in interactive mode. This option comes in handy when you’re running code that compares bytes objects, and you want to get a warning if a string or integer value gets in the middle of a comparison:
The -b option in this example makes the interpreter display a warning when it finds operations that compare bytes with either strings or int values. If you don’t use this option, then no warning is shown:
As in the previous example, the comparison returns False because the values are of different data types. However, in this final example, you don’t get any warning that helps you understand why you’re getting this result.
This is just a sampling of the options that may come in handy when you’re using Python in interactive mode. For a complete list of command-line options, check out the Python documentation.
Exiting the Current Python REPL Session
If you’re used to working on your command line or terminal, then you probably don’t like closing and opening terminal windows all the time. Your regular workflow may go through executing CLI tools, closing them when the work is done, and returning to your current shell session.
This may be the case when you’re using Python in interactive mode. Once inside the REPL, you can’t run normal shell commands because you’re inside a different environment. To get back to your normal shell, you need to terminate the REPL session.
There are a few ways to exit an interactive session. You can use either of the following Python options:
These options are built into Python, so they’re available at any time during an interactive session. Both allow you to terminate the current session. Note that the command forms are only available in Python 3.13 or later, as this is a feature of the improved REPL.
Alternatively, you can explicitly raise the SystemExit exception manually with an exit code of 0. You’ll get the same result, and your current REPL session will terminate.
Any of these options will get you out of your current Python interactive session and take you back to the operating system (OS) shell. After this, you can run regular shell commands again.
Another option for terminating a REPL session is to use one of the following keyboard shortcuts, depending on your current operating system:
- Ctrl+D on Unix systems, such as Linux or macOS
- Ctrl+Z and then Enter on Windows systems
These keystrokes signal the end of input to Python’s standard input (stdin), at which point the REPL terminates.
Running Code in a REPL Session
Up to this point, you’ve learned what the Python standard REPL is and why Python developers love it. You’ve also learned how to start a REPL session using the python command and some of its command-line options. Additionally, you’ve learned how to terminate a Python interactive session and return to the operating system shell.
In the following sections, you’ll start entering and executing Python code in an interactive session.
Evaluating Expressions and Simple Statements
Once you’ve launched a Python interactive session from your command line, you can start entering and executing Python code immediately. To do this, get back to your command-line window and run the python command.
When the REPL’s primary prompt (>>>) appears on your screen, type in the following expressions, pressing the Enter key after each of them:
The first expression subtracts two numbers and displays the result. The second expression is a call to the built-in sum() function, which takes a series of values and returns their total sum. In the third example, you execute a Boolean expression that compares two numbers.
The fourth example is an assignment statement that defines and initializes a variable called number. Because assignments don’t return any value, the Python interpreter doesn’t display any output on your screen. Instead, it falls back to the primary prompt immediately. The final example shows how Python displays an error when your code has issues.
While running these examples, note how after executing each expression, the interpreter loops back to the primary prompt (>>>), which lets you introduce a new expression. Now you’ve seen the REPL cycle in action. The Python interpreter has read your expressions, executed them, and printed their corresponding result to finally loop back to the primary prompt.
Running Compound Statements
With the examples in the previous section, you’ve executed simple statements in a Python interactive session. These expressions are known as simple statements because they don’t have an indented code block.
Python also has compound statements, such as conditionals, loops, and with statements. Compound statements require an indented code block. The Python interpreter has a secondary prompt that lets you enter the code block of compound statements.
Consider the following example of a conditional statement:
In this code snippet, you first define a variable to hold a number. Next up, you start a conditional statement.
Once you type the colon character (:) and press Enter, you get three dots (...) on your screen. These dots represent the REPL’s secondary prompt. This prompt on your screen means that you can enter the required indented blocks of your current compound statement.
When it comes to entering indented code blocks, keep in mind that the standard REPL supports auto-indentation starting in Python 3.13. In previous versions, you’ll get no indentation:
If you’re using a Python version earlier than 3.13, then you must provide the appropriate indentation manually for any indented code block that you need to enter. Otherwise, you’ll get an IndentationError, like in the example above.
Dealing With Explicit and Implicit Line Continuations
Another situation where the REPL’s secondary prompt appears is when you need to use line continuations. A line continuation occurs when you explicitly join multiple physical lines into a single logical line using the backslash (\) character:
This assert statement performs two checks on number. First, it uses the built-in isinstance() function to check if the value is an integer number. Then it checks whether the input value is greater than 0. If either of these conditions fails, then the statement raises an AssertionError with the provided message as an argument.
Line continuations also happen when you use several physical lines to write an expression delimited by a pair of brackets—for example, when you define a list, tuple, or dictionary:
Once you open a bracket, such as [], (), or {}, and press Enter, you get the REPL’s secondary prompt. This is known as implicit line joining.
You can also use implicit line joining in other contexts, such as math and Boolean expressions, function definitions and calls, list comprehensions, and generator expressions. In short, implicit line continuation will appear in all those Python constructs that accept some type of brackets, including [], (), or {}.
Printing vs Evaluating
When you run Python in interactive mode, you’ll notice that the interpreter immediately displays the resulting value of any expression. The interpreter doesn’t display anything for other statements that don’t generate return values. That’s the case with assignment statements, as you already learned.
The Python REPL behaves that way because its primary goal is to provide immediate feedback on how your code works. This behavior makes using the built-in print() function almost unnecessary when you’re working interactively.
However, there’s at least one use case for print() in REPL sessions. You need to use print() when you want to display the result of an expression that can return None, which is Python’s null value.
For example, a common error that some Python beginners make when they start to learn about lists is to expect new lists from calls to list methods, such as .append(), .sort(), and the like:
Because these method calls don’t issue any output to the screen, it may seem that they did nothing. Most list methods run their intended transformation or computation in place. In other words, list methods often modify the underlying list object instead of creating a new one. Because of this, most list methods return None, which the REPL automatically ignores. As a result, nothing shows up on your screen.
If you ever need to display None in a REPL session, then you must use the print() function:
In this code snippet, you use print() to show the return value of .append(), which is None, as you can see.
Note that you can always access the content of a given variable by typing the variable’s name and pressing Enter after it, as you did with numbers. However, if the variable is currently pointing to None, then you won’t get anything on your screen. You’ll have to use print(), as you did with value.
Flagging and Understanding Errors
When an error occurs in a REPL session, the interpreter automatically prints the corresponding error message and traceback. Then, it loops back to the REPL’s primary prompt. In the following examples, you’ll see this behavior in action:
In the first example, the string literal isn’t properly closed with a double quote ("). This raises a SyntaxError. The second example raises a ZeroDivisionError exception because you’re trying to divide 42 by 0. In the final example, you call the built-in sum() function without arguments, which raises a TypeError.
All these errors are immediately printed on the screen. This behavior allows you to quickly and carefully inspect the error message and traceback in order to track the underlying issue and fix your code.
Using the _ Implicit Variable
Every time you run an expression, the REPL internally stores the resulting value in an internal variable whose name is a single underscore (_). You can access and use this variable like any other variable in Python.
Here are a couple of examples that show the implicit _ variable in action:
In these examples, you evaluate expressions that produce a return value, which is automatically assigned to the _ variable every time.
When it comes to function calls, if the target function returns a value different from None, then _ will hold that value. In contrast, if the function returns None, then the _ variable will keep the value of the preceding operation:
The built-in pow() function computes the power of a number to a given exponent, returning the result. Because the function’s result differs from None, the _ variable is automatically reassigned. In contrast, if you call a function that returns None, like print(), then the _ variable remains unchanged.
In the example below, you use an assignment statement to create and initialize a counter variable:
Assignments aren’t expressions, so they don’t return any value. Instead, they store a reference to a value in a variable. In this case, the _ variable isn’t updated after running the assignment. That’s why this variable still contains the number 16 from the previous examples.
Note that accessing a variable in an interactive session returns the value referenced by the variable. In this case, that value is also assigned to the _ variable.
Because _ is a regular Python variable, you can use it in expressions and statements:
In this example, you first create a list of values. Then, you call len() to get the number of values in the list. Python automatically stores this value in the _ variable. Finally, you use _ to compute the average of your list of values.
Keep in mind that the _ variable is only implicitly defined in interactive mode. If you run your code in script mode, then you won’t get this implicit behavior, and trying to use _ without a manual definition will cause a NameError exception.
Reloading Imported Modules
Say that you’re writing a Python module with some functions for one of your projects. At the same time, you’re using Python in interactive mode to test the module’s code in real time. For example, say that you have the following module:
In this file, you define a greet() function that prints a greeting message on the screen. Here’s how to load and use this code from a REPL session:
Now say that you want to add a new argument to your function. The argument will be a Boolean flag that allows printing the greeting message in uppercase letters. To do this, you modify the function to look something like this:
This update allows you to call greet() with an upper argument. If you set the argument to True, then the message will be in uppercase letters. Now you’re eager to try your changes in your REPL session. So, you import the module again, hoping to run the new version of greet() as follows:
What? An unexpected argument? For efficiency reasons, running the import again after updating something in greeting.py doesn’t reload the module.
If you want to work around this behavior without terminating your current REPL session and starting a new one, then you can use the reload() function from the importlib module:
Now your function works! The reload() function has taken care of loading the new version of your greeting.py module. You can use this trick whenever you’re working on a module in your code editor and testing your changes in a REPL session.
Now that you’ve learned the basics of entering and executing code in a Python interactive shell, it’s time to explore and learn about a few editing features that the standard REPL provides.
Editing Code in the Python REPL
The Python standard REPL provides handy editing features to make working interactively more productive. You get a persistent input history, typically saved to ~/.python_history, quick navigation with the arrow keys, and basic autocompletion.
Starting with Python 3.13, the standard REPL is based on PyPy’s pyrepl, which is written in Python and designed for extensibility and safety. It’s also a more capable interactive shell with a modern set of features:
- Color by default: Take advantage of colorized prompts and tracebacks. You can also control this behavior with the
PYTHON_COLORSorNO_COLORenvironment variables. - Quick REPL commands: Use
exit,quit,help, andclearas commands rather than function calls with parentheses. - Built-in help browser: Press F1 to open a help viewer in a pager so you can browse docs for Python, modules, and objects.
- Persistent history browser: Press F2 to open your command history in a pager and keep it across sessions so you can copy and reuse code.
- Multiline editing: Edit and rerun entire code blocks—functions, classes, loops—as a single unit. The block structure is preserved in your history.
- Robust pasting and paste mode: Paste whole scripts or larger code blocks reliably by default. Optionally, you can access paste mode with F3, although direct pasting usually works without issue.
- Smarter tab completion: Completions update as you type and hide irrelevant suggestions to reduce noise.
In Python 3.14, the REPL has taken another leap forward by including the following improvements:
- Extended autocompletion: Covers module and submodule names in import statements
- Live syntax highlighting: Makes your interactive code as readable as in your favorite code editor or IDE
You don’t need to perform any extra installation or configuration to start using these new features, as long as your terminal supports ANSI color output.
Code History and Navigation
The standard REPL logs a complete history of all the code that you’ve typed and run while working in interactive mode. This history is saved to a file called .python_history, typically located in your home directory.
While in interactive mode, you can browse this history by using the arrow keys on your keyboard. With the Up key, you can go back in history. With Down, you can go forward in history. The navigation starts from the end of the history file and goes up. Every time you press the Up key, you jump to the previous line of code in your history.
Once you find the line or block you want, edit it as needed and press Enter to accept it.
Before Python 3.13, you could only navigate the history one line at a time. This is counterintuitive when you want to reuse a compound statement with an indented block because you don’t get the entire statement—only individual lines that keep their indentation.
Starting with Python 3.13, you can use the arrow keys on the primary prompt to navigate the history. If the REPL finds a compound statement with an associated code block, then you’ll get the whole code snippet. Here’s a quick example of a function definition:
Pressing Up will recall the most recent single-line or multiline block. You can modify a multiline block by navigating it with the arrow keys. Once updated, you can accept the code by pressing Enter at the last line in the block.
Finally, in Python 3.13, you can press F2 in a REPL session to open a pager that shows your input history without prompts and outputs. This tool allows you to browse your code history to find a specific piece of code. Once you locate the desired snippet, you can select and copy it to reuse in a program or module.
You can use the up and down arrow keys to navigate the history, and press the Q key to leave the code history pager.
Auto-Indentation
Before Python 3.13, entering compound statements in the REPL required manual indentation. Forgetting to indent would raise an error, as you’ve seen:
Starting with Python 3.13, after typing the colon in a compound statement’s header, the next line will automatically indent to the next level:
The standard REPL in Python 3.13 and later manages indentation automatically for you, which is a great productivity booster. It also helps you avoid accidental IndentationError exceptions.
Safe Multiline Paste and Paste Mode
Pasting multiline or indented code is more reliable in Python 3.13 and later:
If you have issues pasting large or complex code blocks, then you can press F3 to activate the paste mode. In this mode, the prompt changes to (paste). Any pasted code is then accepted exactly as written:
You can exit paste mode by pressing F3 again. In some situations, pasting code that contains indentation or blank lines, or pasting without activating paste mode, may cause unexpected errors.
Quick REPL Commands
In Python 3.13 and later, certain REPL commands no longer require you to call them as functions with parentheses. These commands include the following:
exitorquit: Exit the interpreterhelp: Access the help systemclear: Clear the screen
Now you can type any of these commands and press Enter to run the associated action. You can still use parentheses and type something like exit() if you prefer. Additionally, you can press F1 to open the Python help system directly.
Note that these commands aren’t reserved. That means you can shadow them with a variable assignment:
Here, you create a variable named exit, effectively disabling the exit command. To terminate your REPL session, you can either delete the exit variable or use one of the alternative ways to exit the interpreter.
Code Autocompletion
The standard Python REPL supports Tab completion to help you write code with fewer keystrokes. When you type the beginning of a name and press Tab, the REPL will try to complete it automatically or show a list of possible matches.
Before Python 3.13, autocompletion acted on the following contexts:
- Keywords
- Built-in functions, data types, and exceptions
- Names defined in your current namespace
- Names of imported objects, modules, and packages
- Object, attribute, and method names when using dot notation
For example, when you start to type a Python keyword, you can press Tab to trigger autocompletion. Python will search in its list of keywords and complete your input as expected. This works similarly for the rest of the names in your current namespace.
When you type the name of an object and type a dot to access an attribute or method (member) on that object, you can also press Tab twice to display a list of members:
The resulting list gives you a complete context of the current object’s capabilities so that you can use the right tool. If you start typing the name of a member and press Tab, then Python will complete the name for you.
If there are several names that start with the entered text, then you’ll get a filtered list by pressing Tab again:
Python 3.13 refined autocompletions to improve your user experience:
Now, when you press Tab after the dot, you get a message indicating that the object has several members. You can press Tab again to get the list of members:
Once you have this list displayed, Python filters suggestions more smoothly as you type extra characters, and there’s no need to press Tab again. For example, if you start to type .re, you’ll see how the REPL filters the names:
Python 3.14 extends the autocompletion logic to recognize import contexts and suggest module or package names accordingly. Now, when you type an import or from ... import statement and press Tab, the REPL will search the import path for available module names matching the partial text.
For example, if you type import and then press Tab twice, you’ll get the complete list of currently available modules and packages:
If you start typing a module’s name like pat and press Tab, the REPL will automatically complete the pathlib name because it matches uniquely with the partial text.
Similarly, if you type something like import lo and press Tab after lo, then you’ll get a message saying that the match isn’t unique. Once there, you can press Tab again to get the complete list of matching names or continue typing to make the search pattern more specific:
In this example, the REPL filters the names so you only get the modules that start with lo. Now you can quickly pick which one you want to use.
Syntax Highlighting
Python 3.14 introduced live syntax highlighting in the standard REPL. This means that as you type, keywords, strings, numbers, operators, and other syntax tokens are colored in terminals that support ANSI escape codes. This makes interactive sessions easier to scan and closer to an editor or IDE experience.
Here’s a quick example of how the syntax highlighting works:
In a supporting terminal, keywords, strings, built-in names, comments, and other tokens are nicely colored. Tracebacks are also highlighted, with filenames, line numbers, and error types emphasized for better readability.
In the Python 3.14 Preview: REPL Autocompletion and Highlighting tutorial, you can learn how the syntax highlighting feature works and how to customize it.
Getting Help and Introspecting Code in the REPL
An important feature of any coding environment like an IDE, editor, or REPL is the ability to quickly access help and guidance about using the language, libraries, and tools that you’re working with.
If you’re using the standard REPL, then you’ll have a few tools that allow you to get help and introspect your code depending on your needs and specific context.
Using Python’s Built-in Help System
The built-in help() function gives you access to Python’s help system. You can use this function in two main ways:
- With no arguments to enter Python’s help system
- With an object or its name as a string to access the object’s help page
In Python 3.13 and later, you can also enter the help system using the help command or by pressing F1, as you already learned:
Once you run this, you’ll immediately notice that the prompt changes from >>> to help>. This new prompt reminds you that you’re in the interactive help system.
In help mode, you can enter keywords, module names, function names, or any other name. The help system will search for the target name and present the associated documentation page. To try this functionality out, go ahead and type sys at the help> prompt, then press Enter. You’ll get an output like the following:
To navigate the page, you can use the Up and Down keys or the Enter key to move down. To exit the page, press the Q key on your keyboard.
The help system allows you to search for different topics. You can get the whole list of available topics by typing topics and pressing the Enter key:
Next, you can just type the desired topic name and press Enter. For example, here’s the page for the ASSERTION topic:
In this example, you first search for the ASSERTION topic. This search finds and shows the corresponding help page. You can also search for keywords, built-in names, standard-library modules, and more.
Once you’ve found the required information, you can exit the help system by typing q or quit and then pressing Enter. This will return you to your REPL session.
When you call help() with an object as an argument, you get its associated help page, which typically displays information from the object’s docstrings. It may also include a list of methods and attributes.
For example, here’s a fragment from the page of the str class that you can access by typing help(str) in your REPL session:
In this example, you use the str class object as an argument to help(). Again, you can use the Up and Down keys to move through the page. When you reach the desired information, you can press the Q key to exit the page viewer.
If you use a string as an argument to help(), then the help system looks for it as the name of a module, function, class, method, keyword, or documentation topic. The corresponding help page is then displayed on the screen.
For example, say that you want to get help on the pathlib module, but you haven’t imported it yet. You can then run help() with the string "pathlib" as an argument. You’ll get something like the following:
The call to help() with the "pathlib" string as an argument displays the module’s help page. Note that if you call help() with the pathlib name as an argument, then you’ll get a NameError because you haven’t imported the module into your current namespace.
Introspecting Your Code Dynamically
When you’re working in a REPL session, you have direct access to some Python built-in tools that you can use to introspect your code and obtain more information and context on the objects that you’re working with.
Some of these built-in tools include the following:
| Function | Description |
|---|---|
| dir() | Returns the list of names in the current local scope when you call it with no arguments. Attempts to return a list of valid attributes for the object passed as an argument. |
| vars() | Returns the .__dict__ attribute for a module, class, instance, or any other object with this attribute. The .__dict__ attribute holds a list of names pertaining to the underlying object. |
| locals() | Returns a dictionary representing the names in the current local scope. |
| globals() | Returns the dictionary representing the current global scope. |
| type() | Returns the type of an object when you call it with that object as the only argument. |
You can use any of these built-in functions to introspect your code and retrieve useful information that you can later use in your debugging process.
For example, say that you’re working with dictionaries and want to get a list of all the methods and attributes in this data type. You can do something like this:
The output in this example shows a list of names as strings. This list includes the attributes and methods defined in the dict class.
The vars() function works similarly to dir() but returns a dictionary of name-object pairs instead of a list.
The locals() and globals() functions can also be useful when you want to know the names defined in a given scope in your code. Finally, the type() function helps you determine the data type or class of a given object in your code.
Customizing the Standard REPL
Python lets you customize some of its REPL behaviors and features. To do so, you can use a so-called startup file, a Python file that the interpreter reads and executes when you start an interactive session.
In the following sections, you’ll learn the basics of how to use this file to enhance your user experience while working in the Python standard REPL.
Providing a Startup File
The standard REPL accepts a startup file that you can use to tweak some features or add new features to your interactive sessions. This file only runs for interactive sessions. It doesn’t run when you execute a program as an executable script. So, you don’t have to worry about corrupting important programs.
The startup file may contain any executable Python code. This code will run before the first prompt is displayed in interactive mode.
It’s important to note that the startup file runs in the same namespace where you’ll be running your interactive code. So, objects defined or imported in this file will be available in your interactive session. This behavior is useful when you want to load tools and customize the features of your interactive shell.
Before doing some cool stuff with a startup file, you need to learn how to tell the interpreter which file you want to use as your startup file. You do this by setting the PYTHONSTARTUP environment variable in your system’s shell.
If you’re on Linux or macOS, then you can go to your home folder and run the following commands:
Linux and macOS shells automatically load their corresponding configuration file whenever you fire up a terminal or command-line window. This way, you ensure that the PYTHONSTARTUP variable is always available on your system.
In this example, you set the PYTHONSTARTUP variable to ~/.pythonstartup, which is the path to your target startup file. The file will live in your home directory, and its filename will be .pythonstartup.
Note that the filename isn’t important. You can name it whatever you want. You can als