Find out about bpython: A Python REPL With IDE-Like Features

Using the Python interpreter's default settings, you can run scripts from files (REPL) or interactively execute code in a read-evaluate-print loop. The default REPL included with Python has several restrictions, despite being a powerful tool for exploring the language and learning about its libraries through rapid feedback on your code inputs. Fortunately, many more convenient and programmer-friendly options are available, such as bpython.

Like an integrated development environment, Python enables you to experiment with your code or quickly test an idea without navigating between the contexts of other programmes (IDE). Additionally, Python could be an effective teaching tool in a physical or online classroom.

Beginner's Guide to Python

Instead of being a standalone Python distribution like CPython, PyPy, or Anaconda, bpython is just a pure-Python package that acts as a thin wrapper around a Python interpreter of your choice. You have a lot of versatility because you can utilize bpython on top of any specific Python distribution, version, or virtual environment.

The name of the tool's original creator and maintainer, Bob Farrell, is represented by the letter B in bpython.

Bpython is still a well-liked Python REPL, but it only has a few basic features-like syntax highlighting and auto-completion-borrowed from the fully-featured Python IDEs. Contrary to this minimalist approach, the data science community prefers tools like IPython, a different Python REPL alternative. Many unique commands and other features that are not present in standard Python are added by IPython.

Bpython can be installed on your computer in several waysPackage managers for your operating systems, such as Homebrew or APT, make pre-built versions of bpython available.

However, they are likely out-of-date and pre-programmed to use the system-wide Python interpreter.

Pip is advised for setting up the most recent version of bpython in a virtual environment, even if it may be manually constructed from its source code:

Unfortunately, because bpython depends on the curses library, which is only available on Unix-like systems like macOS and Linux, bpython is not natively supported on Windows. The official documentation refers to a workaround that uses an unofficial Windows binary but no longer appears effective. Installing the Windows Subsystem for Linux (WSL) and then using bpython from there is your best option if you're using Windows.

It's acceptable to have multiple copies of bpython installed across various virtual environments. This enables you to wrap bpython around the particular Python interpreter you initially used to build the virtual environment.

You can launch bpython after installation by using one of the two commands listed below:

It is preferable to use the second command, which invokes bpython as a runnable Python module and is more explicit. By doing this, you can make sure that the bpython programme is running within the virtual environment that is currently active.

The programme installed globally, if any, could be silently reverted to by using the simple bpython command, on the other hand. Additionally, it might be aliased to another shell executable, which would take precedence over the local bpython module.

Now that you know how to set up and use bpython as a substitute for Python's REPL, it's time to investigate its main features. Regardless of your experience level, the following sections will show you numerous ways bpython can boost your productivity as a Python programmer.

Spot Mistakes Quickly

Python's standard REPL is like a vintage black-and-white TV set compared to bpython. Although it effectively conveys information, there are times when you would prefer to see something in colour for better clarity. That's especially crucial when editing code because every little detail counts. So perhaps the most typical features of any good IDE or code editor are syntax highlighting and bracket matching.

bpython comes with both features even though it only functions as a text-based user interface (TUI) for the Python REPL. Bracket matching makes it simpler to maintain the correct balance of the opening and closing brackets, and colourful syntax highlighting aids in quickly identifying the structure of your code. Continue reading to learn how those features are used.

Highlighting Syntax

As you write commands into bpython, they are tokenized into literal values like strings, numbers, or Booleans and Python terms, operators, comments, and variables. You can quickly identify the type of language construct you're working with by looking at the colour that corresponds to each token type:

Find out about bpython: A Python REPL With IDE-Like Features

The Pygments library, utilized beneath the surface, performs the tokenizing and colouring instead of bpython directly. You'll discover how to modify the colour theme in bpython later.

Bracket Matching

Python's Bpython syntax highlighter also informs you if your code's opening and closing braces are balanced. When you type a closing bracket, Python will highlight the corresponding opening bracket, and vice versa:

Find out about bpython: A Python REPL With IDE-Like Features

This functions with all types of Python brackets, including square ([]), rounded (()), and curly () brackets. Better yet, when your cursor passes over one of the correct pairs of brackets, bpython will highlight them. This allows you to nest brackets inside of one another.

Improve Your Typing Speed and Accuracy

Your typing speed and recall of function names, arguments, and other details will directly affect how quickly you can code using the standard Python REPL. In contrast, bpython offers helpful suggestions that you can use with auto-completion at the touch of a button. Additionally, it provides contextual history and aids in proper code indentation.

These features can reduce your typing time and help you avoid pesky typos, allowing you to work more quickly and efficiently.

Code Recommendations

As soon as you begin typing something, bpython will use the LEGB rule to search your current lexical scope, built-ins, globals, and Python keywords to find objects with names that match. More characters will help you get more specific results because it only matches names that start with a particular set of characters. Following that, a list of suggestions will appear in alphabetical order:

Find out about bpython: A Python REPL With IDE-Like Features

If you accidentally overshoot, you can cycle through those suggestions by pressing Tab or Shift+Tab. This can be especially useful when your screen cannot accommodate the content.

Finding out what attributes and methods an object has using type introspection is made easier with the help of code suggestions.

Auto-Indentation

In the default Python REPL, you must manually indent each line when writing lengthy code blocks. If you are accustomed to writing code in a feature-rich editor, this can be time-consuming, awkward, and prone to errors. Fortunately, when you press the Enter key, bpython automatically inserts the proper amount of indentation to the next line:

Find out about bpython: A Python REPL With IDE-Like Features

Bpython's standard indentation is four spaces, which adheres to the Python coding conventions outlined in the PEP 8 guideline. If you want a different indentation size, you can change the matching tab-length setting in the bpython setup. Without entering anything on that line, you can press Enter to end the current block of code. This will bring down the level of indentation by one.

Historical Context

Python history in the user's home directory. A file with the name contains the history of your commands. The default Python REPL stores an infinite history of the in-line commands you've previously entered, including those from completed interpreter sessions. Like many other tools, the interactive Python interpreter controls the history by imitating or providing an interface to the GNU Readline library.

Python-hist and has a limit of 1,000 lines. On the other hand, the configuration allows you to increase the default limit for your bpython history, which is stored separately in a file. Despite this, bpython also keeps a contextual history, with different outcomes depending on where in the code you are. Despite these variations, the conceptually identical fundamental commands to access the history are supported by the regular Python REPL and bpython.

You can traverse history by continuously hitting the arrow keys on your keyboard.

One line of code at a time, use the Up arrow to go back in time and the Down arrow to move ahead in time. Press Enter to confirm your decision and repeat one of the previous instructions.

Find out about bpython: A Python REPL With IDE-Like Features

Note that bpython's historical suggestions don't always correspond to their chronological order. Bpython instead eliminates suggestions that don't make sense in the context of your current indentation level.

In contrast to the standard Python REPL, bpython also considers history when you begin typing a line of code that has already been run:

Find out about bpython: A Python REPL With IDE-Like Features

Bpython will display a greyed-out completion as soon as it discovers a historical entry that starts with a matching character sequence. By pressing the Right arrow on your keyboard, you can either accept the suggestion and have it automatically complete or reject it by typing something else.

Attempt not to switch contexts

Humans aren't very good at multitasking, whereas computers are. When switching between tasks in a context, your brain must first save the current state of each task before moving on to the new task and picking up where you left off with the previous task. This consumes time and effort, increases the likelihood of errors, and lowers productivity. Your tools should limit context switching because programmers already have a lot on their plates.

Integrated development environments, or IDEs, solve this issue by combining different software development tools into a single programme.

The following features of the bpython REPL also give you ways to stay focused:

  • Typological reflection: Look into objects during runtime to see who they are made of.
  • Signatures of Functions: View the parameters that functions and methods expect.
  • Docstrings: Read the types and functions described by the users.
  • Source Code: View the object in question's source code.

You no longer need to launch another programme to investigate unknown code and run the danger of forgetting what you were doing because this knowledge is exactly where you need it. We'll examine each of these features in more detail right now.

Runtime Type Analysis

Python's code suggestions are effective everywhere. One is the dot operator (.) in Python, which is used to access an object's members. To prevent an attribute error, you normally need to know the names of the attributes and methods declared in a class beforehand or refer to the relevant documentation or source code. Fortunately, bpython enables runtime object introspection and attribute filtering without ever leaving your terminal.

As an illustration, suppose you're developing a multithreaded application and can't recall the specific name of a particular method or attribute in the threading. Class of threads You can employ bpython in this circumstance as follows:

Find out about bpython: A Python REPL With IDE-Like Features

Explanation: Keep in mind that by default, only members that are publicly accessible are shown since you shouldn't normally alter an object's internal implementation. On rare occasions, you might want to access or alter its internals. To display such private members in bpython, enter one or more underscore characters (_) right after the dot operator.

Since Python supports operator overloading, many suggested members whose names begin with a double underscore are special methods.

The Python Standard Library, additional libraries installed using pip, and customized modules found in your project folder are all examples of modules that the REPL is aware are importable in the current session. Before importing Python modules and packages, you can also use bpython's recommendations to explore them. Press Tab after typing import, one space, and at least one character to display the following suggestions:

Find out about bpython: A Python REPL With IDE-Like Features

Internal modules in bpython don't appear as suggestions unless you ask for them with the leading underscore or double underscore, similar to checking object attributes. After importing a particular module, you can use the same dot operator to look at its contents.

Docstrings and Function Signatures

The function signature, the formal parameters, and their default values are shown in bpython when you type an opening parenthesis to call a function or method. Furthermore, it will state whether an argument is positional, positional-only, keyword-only, or keyword-only

Find out about bpython: A Python REPL With IDE-Like Features

Explanation: The amazing feature of bpython is the ability to display function signatures. When calling a function, Python highlights the name of the current parameter in the function signature to show how many parameters are still required as input values. This can be very useful if the function expects multiple arguments.

Sadly, despite being present in the source code, the types of the arguments or the function's return value are not displayed because this feature doesn't support type hints. Besides, you'll see that some callable objects, like complex(), don't invoke the corresponding bpython function signatures. Bpython may have trouble with those because they are frequently implemented as classes with special methods that make them look and behave like functions.

Function signatures already contain a wealth of useful details that can help you comprehend the purpose of a function or method without consulting its documentation both your sub() function and Python's built-in max() function have docstrings in the example above, which bpython displays. But if it can locate and extract one from the source code, bpython goes above and beyond by displaying a docstring from the function's body.

A docstring is a multiline string literal that comes right after the function signature and describes the function in human-readable language may occasionally provide details on the function arguments or automated doctests that serve as the function's self-test and usage examples. It is more effective to automatically display docstrings instead of accessing the functions. __ doc__ attribute or the built-in help() function in Python.

You can use bpython to reveal the underlying source code if the function signature or the docstring isn't sufficient for you.

Source Code Sneak Peek

Modern code editors enable you to navigate to a symbol's definition by clicking on it and holding down a specific keyboard key. The Python standard library, symbols defined in your project, or a third-party package you installed with pip are all affected by this. By pressing F2 in bpython after entering a certain symbol, you can get a read-only preview of the relevant source code:

Find out about bpython: A Python REPL With IDE-Like Features

Explanation: The name of a module, function, or class can be typed. You'll only see the source code associated with that specific scope, depending on the type of symbol. It's interesting to note that you can ask for the source code of the classes and functions you previously defined while still in the REPL session.

The default terminal pager programme for your operating system, typically the Unix less command, opens when the source code preview is clicked. Scroll up and down with the arrow keys, Page Up and Down, or hit Q to end the current page.

You can also search by using the forward-slash (/), N for the next occurrence, or P for the previous one.

This feature will only function as long as pure-Python source code is accessible, regardless of whether you use bpython or a code editor. On the other hand, if a symbol is a built-in function or was created as an extension module in the C programming language, you won't be able to learn anything about it. Instead, bpython will indicate that it could not locate any source code.

Correct Errors More Immediately

Another area where the standard Python REPL falls short is the ability to edit code. You'll frequently find yourself repeatedly typing the same line of code because mistakes in nested blocks are challenging to correct without starting over.

You may occasionally make mistakes when writing code or decide against a particular implementation, even with bpython's intelligent code suggestions and auto-completion. The bpython REPL's numerous helpful features make it simple to edit and reevaluate your code, enabling you to:

  • One or more lines backward
  • Use an external editor to edit code.
  • import modules again

One or more lines backwards

When using the standard Python REPL, if you make a mistake in the middle of a code block, you must start over and type the entire code block again. In bpython, you can use Ctrl+R to undo just one of the most recent few lines and add new ones by pressing the key combination:

Find out about bpython: A Python REPL With IDE-Like Features

Explanation: Be aware that bpython runs the entire REPL session from scratch every time you return even one line of code, including previously executed unedited lines. Consequently, you need to take extra care to consider any adverse effects before changing an external state, such as when writing to a file, database, or network connection.

Rewinding is a great way to correct a mistake you realized immediately, but it's not ideal for correcting earlier mistakes or making significant changes. Bpython has an additional solution for this.

Edit Code Using an Outside Editor

You can use an external code editor to add or change code in your bpython REPL by pressing the keyboard shortcut Ctrl+X.

Find out about bpython: A Python REPL With IDE-Like Features

Explanation: If you want to define a new function or an entire class, you can add more than one line of code while using the editor. A Python instruction may already be present in the line selected for editing, in which case bpython will save it to a temporary file before loading it into the external editor. Please save the file when you're done editing it, then quit your editor to get back to bpython.

When you shut down the editor, the bpython REPL will know. Then, just like the previous iteration of the rewind feature, it will inject your updated code from the temporary file into the active session and reevaluate it.

You can edit your entire REPL session in bpython in addition to editing a single line or a small section of code. To launch your current session in an editor, press F7:

Find out about bpython: A Python REPL With IDE-Like Features

This time, you'll see everything in your REPL session, including the comments from previous instructions. They won't be considered because bpython will eventually reevaluate your session when you close the editor.

Imported Modules Reload

With bpython, you can use any code editor to change helper functions, and classes included in your local modules or packages and have those changes instantly reloaded in the current REPL session. Changing some imported code is a great way to test and debug code without restarting bpython.

Press F6 in bpython to reload your modified modules after saving them in a code editor, then evaluate the entire session since starting the REPL:

Find out about bpython: A Python REPL With IDE-Like Features

Explanation: This function is a crucial resource for exploratory testing. Reloading modules updates the outputs while maintaining the integrity of the current REPL session's instructions. They are reducing the time spent shutting down, starting up Python, and repeatedly typing the same instructions, which can increase productivity.

Additionally, automatic module reloading is supported by the bpython REPL, saving you from manually pressing a button each time you make changes to the code in an external editor.

Remember that the entire session is evaluated again when you manually reload modules or let bpython do it for you automatically. In bpython, press F5 to enable the auto-reload feature:

It will keep track of your imported modules and packages and automatically reload them in the currently open REPL session each time one of their files is saved. It can save you time and vastly improve manual module reloading. You can toggle the auto-reload feature off by pressing F5 once more.

As you can see, bpython provides several code editing features that the default Python REPL lacks, making it simpler to fix mistakes and refactor your code.Bpython, however, is more versatile than that! If you're a teacher, you'll value the ability to export your REPL session and share it with others in a few straightforward ways.

Share Your REPL Session

You can use the bpython REPL as a great teaching tool to demonstrate an idea and then show your coworkers or students in a classroom the resulting code snippet. Once you've finished writing something in bpython, you can save it in a file, share it online, or copy the entire REPL session with all outputs to the clipboard.

Clipboard copy

With just one keystroke, you can copy the contents of your REPL session to the clipboard, which is useful for passing around code snippets or pasting them into a Stack Overflow. But keep in mind that in bpython, the copy-to-clipboard function is disabled by default. Installing the pyperclip library into the virtual environment is necessary before you can enable it so that bpython can import it.

After installation, the default shortcut to launch your REPL session is F10. That's a great way to give others working code examples, especially if you want to include the code's results. The syntax colouring will be lost when copied, so paste it into a Python-compatible application to restore the colours.

Instead of manually pasting the code into a messaging app or text editor, you can also save your current REPL session directly to a local file on your computer.

Saving the file

The standard keyboard shortcut for saving your bpython REPL session to a file is the well-known Ctrl+S key combination, which is used for this purpose by most Windows PC programmes:

Find out about bpython: A Python REPL With IDE-Like Features

It will prompt you to enter the name of the file you want to create in your current working directory or the complete path to the location where you want it saved. You will be given the option to overwrite, add to, or cancel the operation if the file already exists.

The Ctrl+S key combination is a standard hotkey on Unix shells that halt a program's output. Overriding bpython's default actions sends a unique XOFF code to halt data transmission through the terminal.

You can use your terminal session to type the following command to remove this antiquated software flow control:

The benefit of saving bpython code to a file is that the REPL prompts, such as the triple chevron (>>>) or the ellipsis (...), are removed, making the code easier to execute. If you want to share the code with others, you must still send the file as an attachment. Sending your REPL session to a Pastebin can be helpful in this situation.

Deliver to Pastebin

The third way to share code in the bpython programming language is to upload your REPL session to a pastebin or other online text storage service. The default pastebin service supported by the bpython REPL is bpa. st, a pinnwand instance, but you can change it to another service if you'd like. After a brief delay, a shareable URL will be displayed when you press F8 and confirm your selection with Y:

Find out about bpython: A Python REPL With IDE-Like Features

Keyboard Shortcuts

Shortcuts on the keyboard that are linked to particular actions, like clearing the screen or displaying the source code preview. Use the following syntax to define unique key bindings:

The generated configuration file includes mappings for actions and their default keyboard shortcuts that have been commented out. A few of them can be updated and de-commented. You can remap the shortcut for the save action to F4 to avoid a conflict with a widely used global hotkey for pausing your terminal, for instance:

After saving the configuration file, remember to restart bpython for your changes to take effect. When bpython starts, the configuration file is only ever read once.

Discover the quirks of bpython

Like any piece of software, bpython has its shortcomings. The biggest one is probably that it requires some adjusting to function on Windows. Due to its reliance on the curses library, you cannot run it as a native Windows application (WSL). Installing Python using the Windows Subsystem for Linux is your best bet.

When you first come across them, the subtle differences in presentation and behaviour between the standard Python REPL and bpython may surprise you. Tracebacks, for instance, appear slightly different. The REPL may become frozen when the code is pasted into bpython until the entire code has finished running. Printing specific ANSI escape codes can also cause bpython to crash.

Last but not least, despite having a lengthy history, bpython has not yet attained version 1.0. This indicates that the project is still in flux and open to radical modifications. But since bpython is currently quite well-established and trustworthy, it doesn't seem this is the case.

Participate in bpython

The source code for the open-source, MIT-licensed bpython REPL is kept on GitHub. Anyone can contribute to bpython in various ways, such as fixing bugs, enhancing documentation, adding translations, or suggesting new features.

Check out the bpython project's open bitesize-labelled GitHub issues if you want to leave your mark. They ought to be especially suitable to start with and can aid in your familiarisation with the codebase.

First, clone the bpython project to your computer and fork it on GitHub using your name. Then, install your copy of bpython with the necessary dependencies in the editable mode, and create and activate a virtual environment for the cloned project using Python 3.7 or later:

Try this outdated method of installing Python packages using setup.py rather than pyproject. toml if you're having issues installing bpython:

The necessary dependencies ought to be added to your active virtual environment as a result. You can choose to manually install any additional dependencies that might be necessary for development or to enable extra features.

The source code for bpython is currently editable. When you launch bpython, for instance, the Python version's banner is displayed at the top of the screen. Open the args.py module in your preferred code editor now:

When you run the module, changes like these will be visible immediately in your virtual environment because you installed bpython in editable mode. Try it! What you'll see will resemble this:

The bpython REPL can be altered however you like. When satisfied with your modification, open a pull request to the original repository and prepare to contribute back. Not bad, huh?

Conclusion

Well done! Any Python interpreter can now have the bpython REPL added on top of it, allowing you to change its settings and utilize all of its IDE-like features. Perhaps from now on, you'll use bpython as your default Python REPL! With satisfaction, you can reflect on everything you've learned about bpython and how it performs better than the default Python REPL.

Learning a new tool can occasionally be intimidating. However, if you invest the time to become accustomed to bpython, you'll be rewarded with strong capabilities and increase your productivity as a Python programmer.






Latest Courses