ELPY(1) | Elpy | ELPY(1) |
elpy - Elpy Documentation
Elpy is the Emacs Python Development Environment. It aims to provide an easy to install, fully-featured environment for Python development.
Contents:
Elpy is an extension for the Emacs text editor to work with Python projects. This documentation tries to explain how to use Elpy to work on Python project using Emacs, but it does not aim to be an introduction to either Emacs or Python.
You can read a quick tour of Emacs, or read the built-in tutorial by running C-h t in the editor. That is, you hold down the control key and hit h (the canonical help key in Emacs), release both, and hit t (for tutorial).
For Python, you can read the basic tutorial. If you already know Python, you should check out some best practices.
Once you have these basics, you can go on to install Elpy.
The main Elpy package is installed via the Emacs package interface, package.el. First, you have to add Elpy's package archive to your list of archives, though. Add the following code to your .emacs file and restart Emacs:
(require 'package) (add-to-list 'package-archives
'("melpa-stable" . "https://stable.melpa.org/packages/"))
Now you can run M-x package-refresh-contents to download a fresh copy of the archive contents, and M-x package-install RET elpy RET to install elpy. If you want to enable Elpy by default, you can simply add the following to your .emacs:
(package-initialize) (elpy-enable)
Congratulations, Elpy is now successfully installed!
In order to use all the features (such as navigation with M-.), you'll need to install some python libraries. You can do that easily by typing M-x elpy-config RET, and following the instructions.
Once installed, Elpy will automatically provide code completion, syntax error highlighting and function signature (in the modeline) for python files.
Elpy has quite a lot of keybindings, but the following ones should be enough to get you started:
C-c C-c evaluates the current script (or region if something is selected) in an interactive python shell. The python shell is automatically displayed aside of your script (if not already there).
C-RET evaluates the current statement (current line plus the following nested lines).
C-c C-z switches between your script and the interactive shell.
C-c C-d displays documentation for the thing under cursor (function or module). The documentation will pop in a different buffer, that can be closed with q.
Elpy offers a lot of features, including code navigation, debugging, testing, refactoring, profiling and support for virtual environments. Feel free to explore the documentation, everything is there !
You can easily configure Elpy to your own preferences. All Customize Options below are accessible via this interface. Elpy builds heavily upon existing extensions for Emacs. The configuration interface tries to include the options for those as well.
Missing packages can be installed right from this interface. Be aware that this does use your currently-selected virtual env. If there is no current virtual env, it will suggest installing packages globally. This is rarely what you want.
Elpy works by starting a Python process in the background and communicating with it through a basic Remote Procedure Call (RPC) interface. Ideally, you should never see this process and not worry about it, but when things don't work as expected, it's good to know what's going on in the background.
Every project and virtual env combination gets their own RPC process. You can see them both in the process list (M-x list-process) as well as in the buffer list (C-x C-b) as buffers named *elpy-rpc[...]*.
By default, Elpy will also find the library root of the current file and pass that to the RPC functions. The library root is the directory from which the current file can be imported.
There are a few options and commands related to the RPC process.
Please do note that this is not an interactive interpreter, so do not set this to "ipython" or similar.
When Elpy communicates with the RPC process, it often needs to tell Python about the contents of the current buffer. As the RPC protocol encodes all data in JSON, this can be a bit slow for large buffers. To speed things up, Elpy can transfer file contents in temporary files, which is a lot faster for large files, but slightly slower for small ones.
For introspection and analysis of Python sources, Elpy mainly relies on Jedi. Jedi is known to have some problems coping with badly-formatted Python.
Elpy has full support for Python's virtual envs. Every RPC process is associated with a specific virtual env and completions are done based on that environment.
Outside of RPC processes, though, it is not easy to have more than one virtual env active at the same time. Elpy allows you to set a single global virtual env and change it whenever you like, though.
The pyvenv-workon command will allow auto-completion of existing virtual envs and also supports virtualenvwrapper's setup hooks to set environment variables.
Elpy won't pollute your Emacs command namespaces, but it might be an idea to create an alias for the workon command:
(defalias 'workon 'pyvenv-workon)
As the last concept, Elpy has a number of optional features you can enable or disable as per your preferences.
Elpy is an extension to Emacs, and as such the standard bindings in Emacs are available. This manual is not meant to be an introduction to Emacs, but this section will still highlight some features in Emacs that are especially useful for Python editing.
Movement keys in Emacs often use fbnp for forward, backward, next (down) and previous (up). k and backspace (DEL) are for deleting. These are combined with the Control, Meta and Control-Meta modifiers. Control generally refers to the simplest form. C-f moves one character forward. Meta changes this to affect words, that is, consecutive sequences of alphanumeric characters. The Control-Meta combination then affects whole expressions.
In the following table, | refers to the position of point.
Before | Key | After |
|hello_world | C-f | h|ello_world |
|hello_world | M-f | hello|_world |
|hello_world | C-M-f | hello_world| |
Expression-based commands will also work on strings, tuples, dictionaries, or any balanced groups of parentheses. This works for all movement keys (f, b, n, p`), with next and previous moving to the next or previous group of parens. It also works with forward and backward deletion (d and DEL/<backspace>, respectively) for character and word groups, but not for expressions. To delete the expression after point, use C-M-k. For the expression before point, you can use C-M-b C-M-k.
If you enable subword-mode, Emacs will also consider CamelCase to be two words instead of one for the purpose of these operations.
In addition to the above, Emacs also supports moving up or down inside nested parentheses groups. C-M-d will move down into the next enclosed group of parentheses, while C-M-u will move up to the directly enclosing group of parentheses.
Finally, a lot of Elpy's commands change their behavior when the prefix argument is given. That is, hit C-u before the command. In Elpy, the prefix argument often disables any attempt by the command at being smart, in case it would get it wrong.
Elpy supports the notion of projects, a related collection of files under a common directory. This common directory is called the project root. A number of Elpy's commands work on all files inside the project root.
A prefix argument enables "do what I mean" mode. On an import statement, it will try to open the module imported. Elsewhere in a file, it will look for an associated test or implementation file, and if found, open that. If this fails, either way, it will fall back to the normal find file in project behavior.
If the current file is called foo.py, then this will search for a test_foo.py in the same directory, or in a test or tests subdirectory. If the current file is already called test_foo.py, it will try and find a foo.py nearby.
This command uses find-file-in-project under the hood, so see there for more options.
This is basically a grep -r through the project.
In addition to these two commands, elpy-check also supports optionally checking all files in the current project.
Elpy's idea of the project root and which files belong to a project and which don't can be influenced as well.
To configure Elpy specifically for a single project, you can use Emacs' Directory Variables. Elpy provides a simple interface to this.
This only takes effect in new buffers.
When you type Python code, Elpy will try and figure out possible completions and provide them in a suggestion window. If Elpy doesn't do so automatically, you can force it to complete right where you are.
You can use cursor keys or M-n and M-p to scroll through the options, RET to use the selected completion, or TAB to complete the common part.
On any completion option, C-d or <f1> will display a temporary window with documentation. C-w will display a temporary window showing the source code of the completion to get some context.
Elpy uses Company Mode for the completion interface, so its documentation is a good place for further information.
Elpy supports some advanced navigation features inside Python projects.
If you use an Emacs version superior to 25, elpy will define the necessary backends for the xref package.
Emacs can run a Python interpreter in a special buffer, making it much easier to send code snippets over. Elpy provides additional functionality to seamlessly work with interactive Python in a style similar to ESS.
Elpy uses the Python interpreter setup from the Emacs python package. This section briefly summarizes some common setups; add the one you need to your .emacs file. Note that the code below (and Elpy in general) require at least Emacs 24.4.
Use the Python standard interpreter (default):
(setq python-shell-interpreter "python"
python-shell-interpreter-args "-i")
Use Jupyter console (recommended for interactive Python):
(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")
Use IPython:
(setq python-shell-interpreter "ipython"
python-shell-interpreter-args "-i --simple-prompt")
Note that various issues with plotting have been reported when running IPython 5 in Emacs under Windows. We recommend using Jupyter console instead.
If you have an older version of IPython and the above code does not work for you, you may also try:
(setenv "IPY_TEST_SIMPLE_PROMPT" "1") (setq python-shell-interpreter "ipython"
python-shell-interpreter-args "-i") As an IPython_ user, you might be interested in the `Emacs IPython Notebook`_ or an `Elpy layer`_ for Spacemacs_, too.
By default, Elpy tries to find the root directory of the current project (git, svn or hg repository, python package or projectile project) and starts the python interpreter here. This behaviour can be suppressed with the option elpy-shell-use-project-root.
(add-hook 'elpy-mode-hook (lambda () (elpy-shell-toggle-dedicated-shell 1)))
(add-hook 'elpy-mode-hook (lambda () (elpy-shell-set-local-shell (elpy-project-root))))
Elpy provides commands to send the current Python statement (e), function definition (f), class definition (c), top-level statement (s), group of Python statements (g), cell (w), region (r), or buffer (b) to the Python shell for evaluation. These commands are bound to prefix C-c C-y, followed by the single character indicating what to send; e.g., C-c C-y e sends the Python statement at point.
Each of the commands to send code fragments to the shell has four variants, one for each combination of: whether or not the point should move after sending ("step"), and whether or not the Python shell should be focused after sending ("go"). Step is activated by C-, go by S-. For example:
Also bound to C-RET.
Elpy provides support for sending multiple statements to the shell.
If the point is within a statement, send the group around this statement. Otherwise, go to the top-level statement below point and send the group around this statement.
Note that elpy-shell-codecell-beginning-regexp must also match the cell boundaries defined here.
The functions for sending the entire buffer have special support for avoiding accidental code execution, e.g.:
When sending the whole buffer, this command will also escape any uses of the if __name__ == '__main__' idiom, to prevent accidental execution of a script. If you want this to be evaluated, pass a prefix argument with C-u.
Also bound to C-c C-c.
The list of remaining commands to send code fragments is:
When package eval-sexp-fu is loaded and eval-sexp-fu-flash-mode is active, the statements sent to the shell are briefly flashed after running an evaluation command, thereby providing visual feedback.
Whenever you save a file, Elpy will run a syntax check and highlight possible errors or warnings inline.
Elpy uses the built-in Flymake library to find syntax errors on the fly, so see there for more configuration options.
With a prefix argument, this will run the syntax check on all files in the current project.
It is possible to create a single virtual env for the sole purpose of installing flake8 in there, and then simply link the command script to a directory inside your PATH, meaning you do not need to install the program in every virtual env separately.
Elpy provides a single interface to documentation.
With a prefix argument, Elpy will skip all the guessing and just prompt the user for a string to look up in pydoc.
If the autodoc module is enabled (not the case by default) the documentation is automatically updated with the symbol at point or the currently selected company candidate.
Testing is an important part of programming. Elpy provides a central interface to testing, which allows for a good workflow for tests.
Elpy's test interface is built around Emacs' compilation framework. Elpy will run test commands as a compilation job, with all the advantages this brings.
Note on Django runners: Elpy tries to find manage.py within your project structure. If it's unable to find it, it falls back to django-admin.py. You must set the environment variable DJANGO_SETTINGS_MODULE accordingly.
This enables a good workflow. You write a test and use C-c C-t to watch it fail. You then go to your implementation file, for example using C-u C-c C-f, and make the test pass. You can use a key bound to recompile (I use <f5> for this) to just re-run that one test. Once that passes, you can use C-c C-t again to run all tests to make sure they all pass as well. Repeat.
For an even more automated way, you can use tdd.el, which will run your last compile command whenever you save a file.
Elpy supports various forms of refactoring Python code.
If the backend does not support finding occurrences (currently only Jedi does), or if a prefix argument is given, this will edit syntactic occurrences instead of semantic ones. This can match more occurrences than it should, so be careful. You can narrow the current buffer to the current function using C-x n d to restrict where this matches.
Finally, if there is a region active, Elpy will edit all occurrences of the text in the region.
This command formats code using yapf , autopep8 or black formatter. If a region is selected, only that region is formatted. Otherwise current buffer is formatted.
yapf and autopep8 can be configured with style files placed in the project root directory (determined by elpy-project-root).
This command uses rope package and provides various refactoring options depending on the context.
Elpy has basic Django support such as parsing either manage.py or django-admin.py (If it does not find manage.py it falls back to django-admin.py) for command completion assistance. Can also start runserver automatically and you can give an ip address and port.
Elpy allows one to profile asynchronously python scripts using cProfile.
Modules are a way of easily extending Elpy with modular extensions. In essence, a module is a function which is called once to initialize itself globally, then once every time elpy-mode is enabled or disabled, and also once if elpy is disabled globally.
To achieve this, a module function receives one or more arguments, the first of which is the command specifier symbol, which can be one of the following:
To activate a module, the user has to add the function to elpy-modules.
A test runner is a function that receives four arguments, described in the docstring of elpy-test-at-point. If only the first argument is given, the test runner should find tests under this directory and run them. If the others are given, the test runner should run the specified test only, or as few as it can.
Test runners should use an interactive spec of (interactive (elpy-test-at-point)) so they can be called directly by the user. For their main work, they can use the helper function elpy-test-run. See the elpy-test-discover-runner for an example.
To make it possible to set the test runner as a file-, directory- or project-local variable, the function symbol should get the elpy-test-runner property with a value of t.
You can set up a working environment for Elpy using pip and cask. After installing Cask, create a new virtual environment and run the setup script in it:
virtualenv ~/.virtualenvs/elpy source ~/.virtualenvs/elpy/bin/activate ./scripts/setup
You can now run ./scripts/test to run Elpy's test suite.
Jorgen Schäfer
2019, Jorgen Schäfer
May 29, 2019 | 1.28.0 |