Emacs: The Best Python Editor?

Emacs: The Best Python Editor?

Finding the right code editor for Python development can be tricky. Many developers explore numerous editors as they grow and learn. One of the most feature-rich editors available is Emacs. In this tutorial, you’ll learn about using Emacs for Python development.

Emacs started in the mid-1970s as a set of macro extensions for a different code editor. It was adopted into the GNU project by Richard Stallman in the early 1980s, and GNU Emacs has been continuously maintained and developed ever since. To this day, GNU Emacs and the XEmacs variant are available on every major platform, and GNU Emacs continues to be a combatant in the Editor Wars.

In this tutorial, you’ll learn about using Emacs for Python development, including how to:

  • Install Emacs on your selected platform
  • Set up an Emacs initialization file to configure Emacs
  • Build a basic Python configuration for Emacs
  • Write Python code to explore Emacs capabilities
  • Run and Test Python code in the Emacs environment
  • Debug Python code using integrated Emacs tools
  • Add source control functionality using Git

For this tutorial, you’ll use GNU Emacs 25 or later, although most of the techniques shown will work on older versions (and XEmacs) as well. You should have some experience developing in Python, and your machine should have a Python distribution already installed and ready to go.

Table of Contents

  • Installation and Basics
    • Installation
    • Basic Emacs
    • Initialization File
    • Customization Packages
  • Emacs for Python Development With elpy
  • Additional Python Language Features
    • Syntax Checking
    • Code Formatting
    • Integration With Jupyter and IPython
  • Testing Support
  • Debugging Support
  • Git Support
  • Additional Emacs Modes
  • Conclusion
Installation and Basics

Before you can explore Emacs and all it has to offer a Python developer, you need to install it and learn some of the basics.

Installation

When you install Emacs, you have to consider your platform. This guide, provided by ErgoEmacs, provides everything you need to get up and running with a basic Emacs installation on Linux, Mac, or Windows.

Once the installation has finished, you can start Emacs:

You should be greeted with the default startup screen.

Basic Emacs

First, let’s go through a quick example to cover some basic Emacs for Python development. You’ll see how to edit a program using vanilla Emacs, and how much Python support is built into the program. With Emacs open, use the following steps to create a quick Python program:

  1. Hit Ctrl+X Ctrl+F to open a new file.
  2. Type sieve.py to name the file.
  3. Hit Enter.
  4. Emacs may ask you to confirm your choice. If so, then hit Enter again.

Now type the following code:

MAX_PRIME = 100


sieve = [True] * MAX_PRIME

for i in range(2, MAX_PRIME):

  if sieve[i]:

    print(i)

      for j in range(i * i, MAX_PRIME, i):

        sieve[j] = False

You may recognize this code as the Sieve of Eratosthenes, which finds all primes below a given maximum. As you type the code, you’ll notice:

  • Emacs highlights variables and constants differently from Python keywords.
  • Emacs indents lines following for and if statements automatically.
  • Emacs changes the indentation to appropriate locations when you hit Tab on an indented line.
  • Emacs highlights the opening bracket or parenthesis whenever you type a closing bracket or parenthesis.
  • Emacs responds as expected to the arrow keys, as well as the Enter, Backspace, Del, Home, End, and Tab keys.

There are some odd key mappings in Emacs, however. If you try to paste code into Emacs, for instance, then you may find the standard Ctrl+V keystroke doesn’t work.

The easiest way to learn which keys do what in Emacs is to follow the built-in tutorial. You can access it by positioning the cursor over the words Emacs Tutorial on the Emacs start screen and pressing Enter, or by typing Ctrl+H T at any time thereafter. You’ll be greeted with the following passage:

Emacs commands generally involve the CONTROL key (sometimes labeled
CTRL or CTL) or the META key (sometimes labeled EDIT or ALT).  Rather than
write that in full each time, we'll use the following abbreviations:

 C-<chr>  means hold the CONTROL key while typing the character <chr>
          Thus, C-f would be: hold the CONTROL key and type f.
 M-<chr>  means hold the META or EDIT or ALT key down while typing <chr>.
          If there is no META, EDIT or ALT key, instead press and release the
          ESC key and then type <chr>.  We write <ESC> for the ESC key.

Important Note: to end the Emacs session, type C-x C-c.  (Two characters.)
To quit a partially entered command, type C-g.

When you scan the text from the passage, you’ll see that Emacs keystrokes are shown in the Emacs documentation using the notation C-x C-s. This is the command to save the contents of the current buffer. This notation indicates that the Ctrl and X keys are pressed at the same time, followed by the Ctrl and S keys.

Note: In this tutorial, Emacs keystrokes are shown as Ctrl+X Ctrl+S.

Emacs uses some terminology that can be traced back to its text-based UNIX roots. Since these terms have different meanings now, it’s a good idea to review them, as you’ll be reading about them as the tutorial progresses:

  • The window you see when you start Emacs is referred to as a frame. You can open as many Emacs frames as you wish, on as many monitors as you wish, and Emacs will track them all.

  • The panes within each Emacs frame are referred to as windows. Emacs frames initially contain a single window, but you can open multiple windows in each frame, either manually or by running special commands.

  • Within each window, the contents displayed are called a buffer. Buffers can contain the contents of files, the output of commands, the lists of menu options, or other items. Buffers are where you interact with Emacs.

  • When Emacs needs your input, it asks in a special one-line area at the bottom of the currently active frame called the mini-buffer. If you ever find yourself there unexpectedly, then you can cancel whatever got you there with Ctrl+G.

Now that you’ve covered the basics, it’s time to start customizing and configuring Emacs for Python development!

Initialization File

One of the great benefits of Emacs is its powerful configuration options. The core of Emacs configuration is the initialization file, which is processed every time Emacs is started.

This file contains commands written in Emacs Lisp, which is executed every time Emacs is started. Don’t worry, though! You don’t need to know Lisp to use or customize Emacs. In this tutorial, you’ll find everything you need to get started. (After all, this is Real Python, not Real Lisp!)

On start-up, Emacs looks for the initialization file in three places:

  1. First, it looks in your home user folder for the file .emacs.
  2. If it’s not there, then Emacs looks in your home user folder for the file emacs.el.
  3. Finally, if neither is found, then it looks in your home folder for .emacs.d/init.el.

The last option, .emacs.d/init.el, is the current recommended initialization file. However, if you’ve previously used and configured Emacs, then you may already have one of the other initialization files present. If so, then continue to use that file as you read this tutorial.

When you first install Emacs, there is no .emacs.d/init.el, but you can create this file fairly quickly. With the Emacs window open, follow these steps:

  1. Hit Ctrl+X Ctrl+F.
  2. Type ~/.emacs.d/init.el in the mini-buffer.
  3. Hit Enter.
  4. Emacs may ask you to confirm your choice. If so, then hit Enter again.

Let’s take a closer look at what’s happening here:

  • You tell Emacs that you want to find and open a file with the keystrokes Ctrl+X Ctrl+F.

  • You tell Emacs what file to open by giving it a path to the file. The path ~/.emacs.d/init.el has three parts:

    1. The leading tilde ~ is a shortcut to your home folder. On Linux and Mac machines, this is usually /home/<username>. On Windows machines, it’s the path specified in the HOME environment variable.
    2. The folder .emacs.d is where Emacs stores all its configuration information. You can use this folder to quickly set up Emacs on a new machine. To do so, copy the contents of this folder to your new machine, and Emacs is good to go!
    3. The file init.el is your initialization file.
  • You tell Emacs, “Yes, I do want to create this new file.” (This step is required since the file doesn’t exist. Normally, Emacs will simply open the file specified.)

After Emacs creates the new file, it opens that file in a new buffer for you to edit. This action doesn’t actually create the file yet, though. You must save the blank file using Ctrl+X Ctrl+S to create it on disk.

Throughout this tutorial, you’ll see initialization code snippets that enable different features. Create the initialization file now if you want to follow along! You can also find the complete initialization file at the link below:

Customization Packages

Now that you have an initialization file, you can add customization options to tailor Emacs for Python development. There are a few ways you can customize Emacs, but the one with the fewest steps is adding Emacs packages. These come from a variety of sources, but the primary package repository is MELPA, or the Milkypostman’s Emacs Lisp Package Archive.

Think of MELPA as PyPI for Emacs packages. Everything you need and will use in this tutorial can be found there. To begin using it, expand the code block below and copy the configuration code to your init.el file:

;; .emacs.d/init.el


;; ===================================

;; MELPA Package Support

;; ===================================

;; Enables basic packaging support

(require 'package)


;; Adds the Melpa archive to the list of available repositories

(add-to-list 'package-archives

             '("melpa" . "http://melpa.org/packages/") t)


;; Initializes the package infrastructure

(package-initialize)


;; If there are no archived package contents, refresh them

(when (not package-archive-contents)

  (package-refresh-contents))


;; Installs packages

;;

;; myPackages contains a list of package names

(defvar myPackages

  '(better-defaults                 ;; Set up some better Emacs defaults

    material-theme                  ;; Theme

    )

  )


;; Scans the list in myPackages

;; If the package listed is not already installed, install it

(mapc #'(lambda (package)

          (unless (package-installed-p package)

            (package-install package)))

      myPackages)


;; ===================================

;; Basic Customization

;; ===================================


(setq inhibit-startup-message t)    ;; Hide the startup message

(load-theme 'material t)            ;; Load material theme

(global-linum-mode t)               ;; Enable line numbers globally


;; User-Defined init.el ends here

As you read through the code, you’ll see that init.el is broken into sections. Each section is separated by comment blocks that begin with two semicolons (;;). The first section is titled MELPA Package Support:

;; .emacs.d/init.el


;; ===================================

;; MELPA Package Support

;; ===================================

;; Enables basic packaging support

(require 'package)


;; Adds the Melpa archive to the list of available repositories

(add-to-list 'package-archives

             '("melpa" . "http://melpa.org/packages/") t)


;; Initializes the package infrastructure

(package-initialize)


;; If there are no archived package contents, refresh them

(when (not package-archive-contents)

  (package-refresh-contents))

This section begins by setting up the packaging infrastructure:

  • Line 7 tells Emacs to use packages.
  • Lines 10 and 11 add the MELPA archive to the list of package sources.
  • Line 14 initializes the packaging system.
  • Lines 17 and 18 build the current package content list if it doesn’t already exist.

The first section continues from line 20:

;; Installs packages

;;

;; myPackages contains a list of package names

(defvar myPackages

  '(better-defaults                 ;; Set up some better Emacs defaults

    material-theme                  ;; Theme

    )

  )


;; Scans the list in myPackages

;; If the package listed is not already installed, install it

(mapc #'(lambda (package)

          (unless (package-installed-p package)

            (package-install package)))

      myPackages)

At this point, you’re all set to programmatically install Emacs packages:

  • Lines 23 to 27 define a list of package names to install. You’ll add more packages as you progress through the tutorial:
    • Line 24 adds better-defaults. This is a collection of minor changes to the Emacs defaults that make it more user-friendly. It’s also a great base for further customization.
    • Line 25 adds the material-theme package, which is a nice dark style found in other environments.
  • Lines 31 to 34 traverse the list and install any packages that are not already installed.

Note: You don’t need to use the Material theme. There are many different Emacs themes available on MELPA for you to choose from. Pick one that suits your style!

After you install your packages, you can move on to the section titled Basic Customization:

;; ===================================

;; Basic Customization

;; ===================================


(setq inhibit-startup-message t)    ;; Hide the startup message

(load-theme 'material t)            ;; Load material theme

(global-linum-mode t)               ;; Enable line numbers globally


;; User-Defined init.el ends here

Here, you add a few other customizations:

  • Line 40 disables the initial Emacs screen containing the tutorial information. You may want to leave this commented out by using a double semicolon (;;) until you’re more comfortable with Emacs.
  • Line 41 loads and activates the Material theme. If you want to install a different theme, then use its name here instead. You can also comment out this line to use the default Emacs theme.
  • Line 42 displays line numbers in every buffer.

Now that you have a complete basic configuration file in place, you can save the file using Ctrl+X Ctrl+S. Then, close and restart Emacs to see the changes.

The first time Emacs runs with these options, it may take a few seconds to start as it sets up the packaging infrastructure. When that’s finished, you’ll see that your Emacs window looks a bit different:

After the restart, Emacs skipped the initial screen and instead opened the last active file. The Material theme is applied, and line numbers have been added to the buffer.

Note: You can add packages interactively after the packaging infrastructure is set up. Hit Alt+X, then type package-show-package-list to see all the packages available to install in Emacs. As of this writing, there are over 4300 available.

With the list of packages visible, you can:

  • Quickly filter the list by package name by hitting F.
  • View the details of any package by clicking its name.
  • Install the package from the package view by clicking the Install link.
  • Close the package list using Q.
Emacs for Python Development With elpy

Emacs is ready out of the box to edit Python code. The library file python.el provides python-mode, which enables basic indentation and syntax highlighting support. However, this built-in package doesn’t provide much else. To properly compete with Python-specific IDEs (Integrated Development Environments), you’ll add more capabilities.

The elpy package (Emacs Lisp Python Environment) provides a near-complete set of Python IDE features, including:

  • Automatic indentation
  • Syntax highlighting
  • Auto completion
  • Syntax checking
  • Python REPL integration
  • Virtual environment support

To install and enable elpy, you add the package to your Emacs configuration. The following change to init.el will do the trick:

(defvar myPackages

  '(better-defaults                 ;; Set up some better Emacs defaults

    elpy                            ;; Emacs Lisp Python Environment

    material-theme                  ;; Theme

    )

  )

Once elpy is installed, you need to enable it. Add the following code just before the end of your init.el file:

;; ====================================

;; Development Setup

;; ====================================

;; Enable elpy

(elpy-enable)


;; User-Defined init.el ends here

You now have a new section titled Development Setup. Line 49 enables elpy.

Note: Unfortunately, Emacs will only read the contents of the initialization file once when it starts. If you make any changes to it, then the easiest and safest way to load them is to restart Emacs.

To see the new mode in action, go back to the Sieve of Eratosthenes code you entered earlier. Create a new Python file and retype the Sieve code directly:

MAX_PRIME = 100


sieve = [True] * MAX_PRIME

for i as range(2, MAX_PRIME):

  if sieve[i]:

    print(i)

    for j in range(i*i, MAX_PRIME, i):

      sieve[j] = False

Note the intentional syntax error on line 4.

This is what your Python file would look like in Emacs:

Auto-indentation and keyword highlighting still work as before. However, you should also see an error indicator on line 4:

This error indicator pops up in the for loop when you typed as instead of in.

Correct that error, then type Ctrl+C Ctrl+C while in the Python buffer to run the file without leaving Emacs:

When you use this command, Emacs will do the following:

  1. Create a new buffer named Python
  2. Open your Python interpreter and connect it to that buffer
  3. Create a new window under your current code window to display the buffer
  4. Send the code to the interpreter to execute

You can scroll through the Python buffer to see which interpreter was run and how the code was started. You can even type commands at the prompt (>>>) at the bottom.

Often, you’ll want to execute your code in a virtual environment using the interpreter and packages specified for that environment. Fortunately, elpy includes the pyvenv package, which provides built-in support for virtual environments.

To use an existing virtual environment in Emacs, type Alt+X pyvenv-workon. Emacs will ask for the name of the virtual environment to use and activate it. You can deactivate the current virtual environment with Alt+X pyvenv-deactivate. You can also access this functionality from the Emacs menu, under Virtual Envs.

You can also configure elpy from within Emacs. Type Alt+X elpy-config to display the following dialog:

You should see valuable debugging information, as well as options to configure elpy.

Now you’ve put all of the basics of using Emacs with Python in place. Time to put some icing on this cake!

Additional Python Language Features

In addition to all of the basic IDE features described above, there are other syntax features you can use with Emacs for Python development. In this tutorial, you’ll cover these three:

  1. Syntax checking with flycheck
  2. Code formatting with PEP 8 and black
  3. Integration with Jupyter and IPython

This is not an exhaustive list, however! Feel free to play around with Emacs and Python to see what other syntax features you can discover.

Syntax Checking

By default, elpy uses a syntax-checking package called flymake. While flymake is built into Emacs, it only has native support four languages, and it requires significant effort to be able to support new languages.

Luckily, there is a newer and more complete solution available! The syntax-checking package flycheck supports real-time syntax checking in over 50 languages and is designed to be quickly configured for new languages. You can read about the differences between flymake and flycheck in the documentation.

You can quickly switch elpy to use flycheck instead of flymake. First, add flycheck to your init.el:

(defvar myPackages

  '(better-defaults                 ;; Set up some better Emacs defaults

    elpy                            ;; Emacs Lisp Python Environment

    flycheck                        ;; On the fly syntax checking

    material-theme                  ;; Theme

    )

  )

flycheck will now be installed with the other packages.

Then, add the following lines in the Development Setup section:

;; ====================================

;; Development Setup

;; ====================================

;; Enable elpy

(elpy-enable)


;; Enable Flycheck

(when (require 'flycheck nil t)

  (setq elpy-modules (delq 'elpy-module-flymake elpy-modules))

  (add-hook 'elpy-mode-hook 'flycheck-mode))

This will enable flycheck when Emacs runs your initialization file. Now you’ll see real-time syntax feedback whenever you use Emacs for Python code editing:

Notice the syntax reminder for range(), which appears at the bottom of the window as you type.

Code Formatting

Love it or hate it, PEP 8 is here to stay. If you want to follow all or some of the standards, then you’ll probably want an automated way to do so. Two popular solutions are autopep8 and black. These code formatting tools must be installed in your Python environment before they can be used.

Once the auto-formatter is available, you can install the proper Emacs package to enable it:

You only need to install one of these in Emacs. To do so, add one of the following highlighted lines to your init.el:

(defvar myPackages

  '(better-defaults                 ;; Set up some better Emacs defaults

    elpy                            ;; Emacs Lisp Python Environment

    flycheck                        ;; On the fly syntax checking

    py-autopep8                     ;; Run autopep8 on save

    blacken                         ;; Black formatting on save

    material-theme                  ;; Theme

    )

  )

If you’re using black, then you’re done! elpy recognizes the blacken package and will enable it automatically.

If you’re using autopep8, however, then you’ll need to enable the formatter in the Development Setup section:

;; ====================================

;; Development Setup

;; ====================================

;; Enable elpy

(elpy-enable)


;; Enable Flycheck

(when (require 'flycheck nil t)

  (setq elpy-modules (delq 'elpy-module-flymake elpy-modules))

  (add-hook 'elpy-mode-hook 'flycheck-mode))


;; Enable autopep8

(require 'py-autopep8)

(add-hook 'elpy-mode-hook 'py-autopep8-enable-on-save)


;; User-Defined init.el ends here

Now, every time you save your Python code, the buffer is automatically formatted and saved, and the contents reloaded. You can see how this works with some badly formatted Sieve code and the black formatter:

You can see that after the file is saved, it’s reloaded in the buffer with the proper black formatting applied.

Integration With Jupyter and IPython

Emacs can also work with Jupyter Notebooks and the IPython REPL. If you don’t already have Jupyter installed, then check out Jupyter Notebook: An Introduction. Once Jupyter is ready to go, add the following lines to your init.el after the call to enable elpy:

;; ====================================

;; Development Setup

;; ====================================

;; Enable elpy

(elpy-enable)


;; Use IPython for REPL

(setq python-shell-interpreter "jupyter"

      python-shell-interpreter-args "console --simple-prompt"

      python-shell-prompt-detect-failure-warning nil)

(add-to-list 'python-shell-completion-native-disabled-interpreters

             "jupyter")


;; Enable Flycheck

(when (require 'flycheck nil t)

  (setq elpy-modules (delq 'elpy-module-flymake elpy-modules))

  (add-hook 'elpy-mode-hook 'flycheck-mode))

This will update Emacs to use IPython rather than the standard Python REPL. Now when you run your code with Ctrl+C Ctrl+C, you’ll see the IPython REPL:

While this is pretty useful on its own, the real magic is in the Jupyter Notebook integration. As always, you need to add a bit of configuration to enable everything. The ein package enables an IPython Notebook client in Emacs. You can add it to your init.el like so:

(defvar myPackages

  '(better-defaults                 ;; Set up some better Emacs defaults

    elpy                            ;; Emacs Lisp Python Environment

    flycheck                        ;; On the fly syntax checking

    py-autopep8                     ;; Run autopep8 on save

    blacken                         ;; Black formatting on save

    ein                             ;; Emacs IPython Notebook

    material-theme                  ;; Theme

    )

  )

You can now start a Jupyter server and work with Notebooks from within Emacs.

To start the server, use the command Alt+X ein:jupyter-server-start. Then provide a folder in which to run the server. You’ll see a new buffer showing the Jupyter Notebooks available in the folder selected:

From here you can create a new Notebook with a selected kernel by clicking New Notebook, or open an existing Notebook from the list at the bottom by clicking Open:

You can complete the exact same task by typing Ctrl+X Ctrl+F, and then typing Ctrl+C Ctrl+Z. This will open the Jupyter Notebook directly in Emacs as a file.

With a Notebook open, you can:

  • Move around the Notebook cells using the arrow keys
  • Add a new cell above the current cell using Ctrl+A
  • Add a new cell below the current cell using Ctrl+B
  • Execute new cells using either Ctrl+C Ctrl+C or Alt+Enter

Here’s an example of how to move around a Notebook, add a new cell, and execute it:

You can save your work using Ctrl+X Ctrl+S.

When you’re done working in your notebook, you can close it using Ctrl+C Ctrl+Shift+3. You can stop the Jupyter server completely by hitting Alt+X ein:jupyter-server-stop. Emacs will ask you if you want to kill the server and close all open Notebooks.

Of course, this is just the tip of the Jupyter iceberg! You can explore everything the ein package can do in the documentation.

Testing Support

Do you write perfect code that has no side-effects and performs well under all conditions? Of course… not! If this sounds like you, though, then you’re free to skip ahead a bit. But for most developers, testing code is a requirement.

elpy provides extensive support for running tests, including support for:

To demonstrate the testing capabilities, the code for this tutorial includes a version of Edsger Dijkstra’s shunting yard algorithm. This algorithm parses mathematical equations that are written using infix notation. You can download the code at the link below:

To start, let’s get a more complete picture of the project by viewing the project folder. You can open a folder in Emacs using Ctrl+X D. Next, you’ll display two windows in the same frame by splitting the frame vertically with Ctrl+X 3. Finally, you navigate to the test file in the left window, and click on it to open it in the right window:

The test file expr_test.py is a basic unittest file that contains a single test case with six tests. To run the test case, type Ctrl+C Ctrl+T:

The results are displayed in the left window. Notice how all six tests were run. You can run a single test in a test file by putting the cursor in that test before typing Ctrl+C Ctrl+T.

Debugging Support

When tests fail, you’ll need to delve into the code to figure out why. The built-in python-mode allows you to use Emacs for Python code debugging with pdb. For an introduction to pdb,

Here’s how to use pdb in Emacs:

  1. Open the debug-example.py file in the PyEval project.
  2. Type Alt+X pdb to start the Python debugger.
  3. Type debug-example.py Enter to run the file under the debugger.

Once it’s running, pdb will split the frame horizontally and open itself in a window above the file you’re debugging:

All debuggers in Emacs run as part of the Grand Unified Debugger library, also called the GUD. This library provides a consistent interface for debugging all supported languages. The name of the buffer created, gud-debug-example.py, shows that the debug window was created by the GUD.

The GUD also connects pdb to the actual source file in the bottom window, which tracks your current location. Let’s step through this code to see how that works:

You can step through code in pdb using one of two keys:

  1. S steps into other functions.
  2. N steps over other functions.

You’ll see the cursor move in the lower source window to keep track of the execution point. As you follow function calls, pdb opens local files as required to keep you moving forward.

Git Support

No modern IDE would be complete without support for source control. While numerous source control options exist, it’s a fair bet that most programmers are using Git.

In Emacs, source control support is provided by the magit package. You install magit by listing it in your init.el file:

(defvar myPackages

  '(better-defaults                 ;; Set up some better Emacs defaults

    elpy                            ;; Emacs Lisp Python Environment

    ein                             ;; Emacs iPython Notebook

    flycheck                        ;; On the fly syntax checking

    py-autopep8                     ;; Run autopep8 on save

    blacken                         ;; Black formatting on save

    magit                           ;; Git integration

    material-theme                  ;; Theme

    )

  )

After you restart Emacs, magit will be ready to use.

Let’s take a look at an example. Open any of the files in the PyEval folder, then type Alt+X magit-status. You’ll see the following appear:

When activated, magit splits the Emacs frame and displays its status buffer in the lower window. This snapshot lists the staged, unstaged, untracked, and any other files in your repo folder.

Most of the interaction you do with magit will be in this status buffer. For example, you can:

  • Move between sections in the status buffer using P for Previous and N for Next
  • Expand or collapse a section using Tab
  • Stage changes using S
  • Unstage changes using U
  • Refresh the contents of the status buffer using G

Once a change is staged, you commit it using C. You’ll be presented with a variety of commit variations. For a normal commit, hit C again. You’ll see two new buffers appear:

  1. The lower window contains the COMMIT_EDITMSG buffer, which is where you add your commit message.
  2. The upper window contains the magit-diff buffer, which displays the changes you are committing.

After entering your commit message, type Ctrl+C Ctrl+C to commit the changes:

You may have noticed the top of the status buffer displaying both the Head (local) and Merge (remote) branches. This allows you to push your changes to the remote branch quickly.

Look in the status buffer under Unmerged into origin/master and find the changes you want to push. Then, hit Shift+P to open the push options, and P to push the changes:

Out of the box, magit will talk to GitHub and GitLab, as well as a host of other source control tools. For more info on magit and its capabilities, check out the full documentation.

Additional Emacs Modes

One of the major benefits of using Emacs over a Python-specific IDE is the ability to work in other languages. As a developer, you might have to work with Python, Golang, JavaScript, Markdown, JSON, shell scripts, and more, all in a single day! Having complex and complete support for all of these languages in a single code editor will increase your efficiency.

There are tons of example Emacs initialization files available for you to review and use to build your own configuration. One of the best sources is GitHub. A GitHub search for emacs.d turns up a plethora of options for you to sift through.

Conclusion

As one of the most feature-rich editors available, Emacs is great for Python programmers. Available on every major platform, Emacs is extremely customizable and adaptable to many different tasks.

Now you can:

  • Install Emacs on your selected platform
  • Set up an Emacs initialization file to configure Emacs
  • Build a basic Python configuration for Emacs
  • Write Python code to explore Emacs capabilities
  • Run and Test Python code in the Emacs environment
  • Debug Python code using integrated Emacs tools
  • Add source control functionality using Git

What's Python IDLE? How to use Python IDLE to interact with Python?

What's Python IDLE? How to use Python IDLE to interact with Python?

In this tutorial, you’ll learn all the basics of using **IDLE** to write Python programs. You'll know what Python IDLE is and how you can use it to interact with Python directly. You’ve also learned how to work with Python files and customize Python IDLE to your liking.

In this tutorial, you'll learn how to use the development environment included with your Python installation. Python IDLE is a small program that packs a big punch! You'll learn how to use Python IDLE to interact with Python directly, work with Python files, and improve your development workflow.

If you’ve recently downloaded Python onto your computer, then you may have noticed a new program on your machine called IDLE. You might be wondering, “What is this program doing on my computer? I didn’t download that!” While you may not have downloaded this program on your own, IDLE comes bundled with every Python installation. It’s there to help you get started with the language right out of the box. In this tutorial, you’ll learn how to work in Python IDLE and a few cool tricks you can use on your Python journey!

In this tutorial, you’ll learn:

  • What Python IDLE is
  • How to interact with Python directly using IDLE
  • How to edit, execute, and debug Python files with IDLE
  • How to customize Python IDLE to your liking

Table of Contents

What Is Python IDLE?

Every Python installation comes with an Integrated Development and Learning Environment, which you’ll see shortened to IDLE or even IDE. These are a class of applications that help you write code more efficiently. While there are many IDEs for you to choose from, Python IDLE is very bare-bones, which makes it the perfect tool for a beginning programmer.

Python IDLE comes included in Python installations on Windows and Mac. If you’re a Linux user, then you should be able to find and download Python IDLE using your package manager. Once you’ve installed it, you can then use Python IDLE as an interactive interpreter or as a file editor.

An Interactive Interpreter

The best place to experiment with Python code is in the interactive interpreter, otherwise known as a shell. The shell is a basic Read-Eval-Print Loop (REPL). It reads a Python statement, evaluates the result of that statement, and then prints the result on the screen. Then, it loops back to read the next statement.

The Python shell is an excellent place to experiment with small code snippets. You can access it through the terminal or command line app on your machine. You can simplify your workflow with Python IDLE, which will immediately start a Python shell when you open it.

A File Editor

Every programmer needs to be able to edit and save text files. Python programs are files with the .py extension that contain lines of Python code. Python IDLE gives you the ability to create and edit these files with ease.

Python IDLE also provides several useful features that you’ll see in professional IDEs, like basic syntax highlighting, code completion, and auto-indentation. Professional IDEs are more robust pieces of software and they have a steep learning curve. If you’re just beginning your Python programming journey, then Python IDLE is a great alternative!

How to Use the Python IDLE Shell

The shell is the default mode of operation for Python IDLE. When you click on the icon to open the program, the shell is the first thing that you see:

This is a blank Python interpreter window. You can use it to start interacting with Python immediately. You can test it out with a short line of code:

Here, you used print() to output the string "Hello, from IDLE!" to your screen. This is the most basic way to interact with Python IDLE. You type in commands one at a time and Python responds with the result of each command.

Next, take a look at the menu bar. You’ll see a few options for using the shell:

You can restart the shell from this menu. If you select that option, then you’ll clear the state of the shell. It will act as though you’ve started a fresh instance of Python IDLE. The shell will forget about everything from its previous state:

In the image above, you first declare a variable, x = 5. When you call print(x), the shell shows the correct output, which is the number 5. However, when you restart the shell and try to call print(x) again, you can see that the shell prints a traceback. This is an error message that says the variable x is not defined. The shell has forgotten about everything that came before it was restarted.

You can also interrupt the execution of the shell from this menu. This will stop any program or statement that’s running in the shell at the time of interruption. Take a look at what happens when you send a keyboard interrupt to the shell:

A KeyboardInterrupt error message is displayed in red text at the bottom of your window. The program received the interrupt and has stopped executing.

How to Work With Python Files

Python IDLE offers a full-fledged file editor, which gives you the ability to write and execute Python programs from within this program. The built-in file editor also includes several features, like code completion and automatic indentation, that will speed up your coding workflow. First, let’s take a look at how to write and execute programs in Python IDLE.

Opening a File

To start a new Python file, select File → New File from the menu bar. This will open a blank file in the editor, like this:

From this window, you can write a brand new Python file. You can also open an existing Python file by selecting File → Open… in the menu bar. This will bring up your operating system’s file browser. Then, you can find the Python file you want to open.

If you’re interested in reading the source code for a Python module, then you can select File → Path Browser. This will let you view the modules that Python IDLE can see. When you double click on one, the file editor will open up and you’ll be able to read it.

The content of this window will be the same as the paths that are returned when you call sys.path. If you know the name of a specific module you want to view, then you can select File → Module Browser and type in the name of the module in the box that appears.

Editing a File

Once you’ve opened a file in Python IDLE, you can then make changes to it. When you’re ready to edit a file, you’ll see something like this:

The contents of your file are displayed in the open window. The bar along the top of the window contains three pieces of important information:

  1. The name of the file that you’re editing
  2. The full path to the folder where you can find this file on your computer
  3. The version of Python that IDLE is using

In the image above, you’re editing the file myFile.py, which is located in the Documents folder. The Python version is 3.7.1, which you can see in parentheses.

There are also two numbers in the bottom right corner of the window:

  1. Ln: shows the line number that your cursor is on.
  2. Col: shows the column number that your cursor is on.

It’s useful to see these numbers so that you can find errors more quickly. They also help you make sure that you’re staying within a certain line width.

There are a few visual cues in this window that will help you remember to save your work. If you look closely, then you’ll see that Python IDLE uses asterisks to let you know that your file has unsaved changes:

The file name shown in the top of the IDLE window is surrounded by asterisks. This means that there are unsaved changes in your editor. You can save these changes with your system’s standard keyboard shortcut, or you can select File → Save from the menu bar. Make sure that you save your file with the .py extension so that syntax highlighting will be enabled.

Executing a File

When you want to execute a file that you’ve created in IDLE, you should first make sure that it’s saved. Remember, you can see if your file is properly saved by looking for asterisks around the filename at the top of the file editor window. Don’t worry if you forget, though! Python IDLE will remind you to save whenever you attempt to execute an unsaved file.

To execute a file in IDLE, simply press the F5 key on your keyboard. You can also select Run → Run Module from the menu bar. Either option will restart the Python interpreter and then run the code that you’ve written with a fresh interpreter. The process is the same as when you run python3 -i [filename] in your terminal.

When your code is done executing, the interpreter will know everything about your code, including any global variables, functions, and classes. This makes Python IDLE a great place to inspect your data if something goes wrong. If you ever need to interrupt the execution of your program, then you can press Ctrl+C in the interpreter that’s running your code.

How to Improve Your Workflow

Now that you’ve seen how to write, edit, and execute files in Python IDLE, it’s time to speed up your workflow! The Python IDLE editor offers a few features that you’ll see in most professional IDEs to help you code faster. These features include automatic indentation, code completion and call tips, and code context.

Automatic Indentation

IDLE will automatically indent your code when it needs to start a new block. This usually happens after you type a colon (:). When you hit the enter key after the colon, your cursor will automatically move over a certain number of spaces and begin a new code block.

You can configure how many spaces the cursor will move in the settings, but the default is the standard four spaces. The developers of Python agreed on a standard style for well-written Python code, and this includes rules on indentation, whitespace, and more. This standard style was formalized and is now known as PEP 8. To learn more about it, check out How to Write Beautiful Python Code With PEP 8.

Code Completion and Call Tips

When you’re writing code for a large project or a complicated problem, you can spend a lot of time just typing out all of the code you need. Code completion helps you save typing time by trying to finish your code for you. Python IDLE has basic code completion functionality. It can only autocomplete the names of functions and classes. To use autocompletion in the editor, just press the tab key after a sequence of text.

Python IDLE will also provide call tips. A call tip is like a hint for a certain part of your code to help you remember what that element needs. After you type the left parenthesis to begin a function call, a call tip will appear if you don’t type anything for a few seconds. For example, if you can’t quite remember how to append to a list, then you can pause after the opening parenthesis to bring up the call tip:

The call tip will display as a popup note, reminding you how to append to a list. Call tips like these provide useful information as you’re writing code.

Code Context

The code context functionality is a neat feature of the Python IDLE file editor. It will show you the scope of a function, class, loop, or other construct. This is particularly useful when you’re scrolling through a lengthy file and need to keep track of where you are while reviewing code in the editor.

To turn it on, select Options → Code Context in the menu bar. You’ll see a gray bar appear at the top of the editor window:

As you scroll down through your code, the context that contains each line of code will stay inside of this gray bar. This means that the print() functions you see in the image above are a part of a main function. When you reach a line that’s outside the scope of this function, the bar will disappear.

How to Debug in IDLE

A bug is an unexpected problem in your program. They can appear in many forms, and some are more difficult to fix than others. Some bugs are tricky enough that you won’t be able to catch them by just reading through your program. Luckily, Python IDLE provides some basic tools that will help you debug your programs with ease!

Interpreter DEBUG Mode

If you want to run your code with the built-in debugger, then you’ll need to turn this feature on. To do so, select Debug → Debugger from the Python IDLE menu bar. In the interpreter, you should see [DEBUG ON] appear just before the prompt (>>>), which means the interpreter is ready and waiting.

When you execute your Python file, the debugger window will appear:

In this window, you can inspect the values of your local and global variables as your code executes. This gives you insight into how your data is being manipulated as your code runs.

You can also click the following buttons to move through your code:

  • Go: Press this to advance execution to the next breakpoint. You’ll learn about these in the next section.
  • Step: Press this to execute the current line and go to the next one.
  • Over: If the current line of code contains a function call, then press this to step over that function. In other words, execute that function and go to the next line, but don’t pause while executing the function (unless there is a breakpoint).
  • Out: If the current line of code is in a function, then press this to step out of this function. In other words, continue the execution of this function until you return from it.

Be careful, because there is no reverse button! You can only step forward in time through your program’s execution.

You’ll also see four checkboxes in the debug window:

  1. Globals: your program’s global information
  2. Locals: your program’s local information during execution
  3. Stack: the functions that run during execution
  4. Source: your file in the IDLE editor

When you select one of these, you’ll see the relevant information in your debug window.

Breakpoints

A breakpoint is a line of code that you’ve identified as a place where the interpreter should pause while running your code. They will only work when DEBUG mode is turned on, so make sure that you’ve done that first.

To set a breakpoint, right-click on the line of code that you wish to pause. This will highlight the line of code in yellow as a visual indication of a set breakpoint. You can set as many breakpoints in your code as you like. To undo a breakpoint, right-click the same line again and select Clear Breakpoint.

Once you’ve set your breakpoints and turned on DEBUG mode, you can run your code as you would normally. The debugger window will pop up, and you can start stepping through your code manually.

Errors and Exceptions

When you see an error reported to you in the interpreter, Python IDLE lets you jump right to the offending file or line from the menu bar. All you have to do is highlight the reported line number or file name with your cursor and select Debug → Go to file/line from the menu bar. This is will open up the offending file and take you to the line that contains the error. This feature works regardless of whether or not DEBUG mode is turned on.

Python IDLE also provides a tool called a stack viewer. You can access it under the Debug option in the menu bar. This tool will show you the traceback of an error as it appears on the stack of the last error or exception that Python IDLE encountered while running your code. When an unexpected or interesting error occurs, you might find it helpful to take a look at the stack. Otherwise, this feature can be difficult to parse and likely won’t be useful to you unless you’re writing very complicated code.

How to Customize Python IDLE

There are many ways that you can give Python IDLE a visual style that suits you. The default look and feel is based on the colors in the Python logo. If you don’t like how anything looks, then you can almost always change it.

To access the customization window, select Options → Configure IDLE from the menu bar. To preview the result of a change you want to make, press Apply. When you’re done customizing Python IDLE, press OK to save all of your changes. If you don’t want to save your changes, then simply press Cancel.

There are 5 areas of Python IDLE that you can customize:

  1. Fonts/Tabs
  2. Highlights
  3. Keys
  4. General
  5. Extensions

Let’s take a look at each of them now.

Fonts/Tabs

The first tab allows you to change things like font color, font size, and font style. You can change the font to almost any style you like, depending on what’s available for your operating system. The font settings window looks like this:

You can use the scrolling window to select which font you prefer. (I recommend you select a fixed-width font like Courier New.) Pick a font size that’s large enough for you to see well. You can also click the checkbox next to Bold to toggle whether or not all text appears in bold.

This window will also let you change how many spaces are used for each indentation level. By default, this will be set to the PEP 8 standard of four spaces. You can change this to make the width of your code more or less spread out to your liking.

Highlights

The second customization tab will let you change highlights. Syntax highlighting is an important feature of any IDE that highlights the syntax of the language that you’re working in. This helps you visually distinguish between the different Python constructs and the data used in your code.

Python IDLE allows you to fully customize the appearance of your Python code. It comes pre-installed with three different highlight themes:

  1. IDLE Day
  2. IDLE Night
  3. IDLE New

You can select from these pre-installed themes or create your own custom theme right in this window:

Unfortunately, IDLE does not allow you to install custom themes from a file. You have to create customs theme from this window. To do so, you can simply start changing the colors for different items. Select an item, and then press Choose color for. You’ll be brought to a color picker, where you can select the exact color that you want to use.

You’ll then be prompted to save this theme as a new custom theme, and you can enter a name of your choosing. You can then continue changing the colors of different items if you’d like. Remember to press Apply to see your changes in action!

Keys

The third customization tab lets you map different key presses to actions, also known as keyboard shortcuts. These are a vital component of your productivity whenever you use an IDE. You can either come up with your own keyboard shortcuts, or you can use the ones that come with IDLE. The pre-installed shortcuts are a good place to start:

The keyboard shortcuts are listed in alphabetical order by action. They’re listed in the format Action - Shortcut, where Action is what will happen when you press the key combination in Shortcut. If you want to use a built-in key set, then select a mapping that matches your operating system. Pay close attention to the different keys and make sure your keyboard has them!

Creating Your Own Shortcuts

The customization of the keyboard shortcuts is very similar to the customization of syntax highlighting colors. Unfortunately, IDLE does not allow you to install custom keyboard shortcuts from a file. You must create a custom set of shortcuts from the Keys tab.

Select one pair from the list and press Get New Keys for Selection. A new window will pop up:

Here, you can use the checkboxes and scrolling menu to select the combination of keys that you want to use for this shortcut. You can select Advanced Key Binding Entry >> to manually type in a command. Note that this cannot pick up the keys you press. You have to literally type in the command as you see it displayed to you in the list of shortcuts.

General

The fourth tab of the customization window is a place for small, general changes. The general settings tab looks like this:

Here, you can customize things like the window size and whether the shell or the file editor opens first when you start Python IDLE. Most of the things in this window are not that exciting to change, so you probably won’t need to fiddle with them much.

Extensions

The fifth tab of the customization window lets you add extensions to Python IDLE. Extensions allow you to add new, awesome features to the editor and the interpreter window. You can download them from the internet and install them to right into Python IDLE.

To view what extensions are installed, select Options → Configure IDLE -> Extensions. There are many extensions available on the internet for you to read more about. Find the ones you like and add them to Python IDLE!

Conclusion

In this tutorial, you’ve learned all the basics of using IDLE to write Python programs. You know what Python IDLE is and how you can use it to interact with Python directly. You’ve also learned how to work with Python files and customize Python IDLE to your liking.

You’ve learned how to:

  • Work with the Python IDLE shell
  • Use Python IDLE as a file editor
  • Improve your workflow with features to help you code faster
  • Debug your code and view errors and exceptions
  • Customize Python IDLE to your liking

Now you’re armed with a new tool that will let you productively write Pythonic code and save you countless hours down the road. Happy programming!

Importance of Python Programming skills

Importance of Python Programming skills

Python is one among the most easiest and user friendly programming languages when it comes to the field of software engineering. The codes and syntaxes of python is so simple and easy to use that it can be deployed in any problem solving...

Python is one among the most easiest and user friendly programming languages when it comes to the field of software engineering. The codes and syntaxes of python is so simple and easy to use that it can be deployed in any problem solving challenges. The codes of Python can easily be deployed in Data Science and Machine Learning. Due to this ease of deployment and easier syntaxes, this platform has a lot of real world problem solving applications. According to the sources the companies are eagerly hunting for the professionals with python skills along with SQL. An average python developer in the united states makes around 1 lakh U.S Dollars per annum. In some of the top IT hubs in our country like Bangalore, the demand for professionals in the domains of Data Science and Python Programming has surpassed over the past few years. As a result of which a lot of various python certification courses are available right now.

Array in Python: An array is defined as a data structure that can hold a fixed number of elements that are of the same python data type. The following are some of the basic functions of array in python:

  1. To find the transverse
  2. For insertion of the elements
  3. For deletion of the elements
  4. For searching the elements

Along with this one can easily crack any python interview by means of python interview questions

Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Python Training

This video on Tkinter tutorial covers all the basic aspects of creating and making use of your own simple Graphical User Interface (GUI) using Python. It establishes all of the concepts needed to get started with building your own user interfaces while coding in Python.

This video on Tkinter tutorial covers all the basic aspects of creating and making use of your own simple Graphical User Interface (GUI) using Python. It establishes all of the concepts needed to get started with building your own user interfaces while coding in Python.

Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Complete Python Masterclass

☞ Learn Python by Building a Blockchain & Cryptocurrency

☞ Python and Django Full Stack Web Developer Bootcamp

☞ The Python Bible™ | Everything You Need to Program in Python

☞ Learning Python for Data Analysis and Visualization

☞ Python for Financial Analysis and Algorithmic Trading

☞ The Modern Python 3 Bootcamp

Original video source: https://www.youtube.com/watch?v=VMP1oQOxfM0