Skip to content

Emacs

Installing Sourcery

  1. Install the lsp-mode LSP client for Emacs.
  2. Install the sourcery-cli pypi package with pip install sourcery-cli. Note down the application path e.g. /path/to/sourcery or C:\path\to\sourcery.exe
  3. Add the following code to your emacs config:
    (lsp-register-client
     (make-lsp-client :new-connection (lsp-stdio-connection '("<Command to run Sourcery>" "lsp"))
                      :initialization-options '((token . "<your_token_here>")
                                                (extension_version . "emacs-lsp")
                                                (editor_version . "emacs"))
                      :activation-fn (lsp-activate-on "python")
                      :server-id 'sourcery
                      :add-on? t
                      :priority 2))
    
  4. Go to your Sourcery Dashboard, copy your token, and replace the <Your token here> section with your token.

Getting Started

Seeing Your First Suggestions

Sourcery scans the currently open Python file. If lsp-modeline-diagnostics-mode is enabled it highlights the relevant lines of code with improvements.

When on a suggestion line, you can hover to see the suggestion, and run the code action to refactor that code.

You can also try out Sourcery by copying this code into a Python file in Emacs:

def merge_nested_if(a, b):
    if a:
        if b:
            return c

Sourcery will suggest merging together the nested if statements so you get:

def merge_nested_if(a, b):
    if a and b:
        return c

How To

Accept a Suggestion

When on a suggestion line, you can hover to see the suggestion, and run the code action to refactor that code.

Skip a Suggestion

When on a suggestion line, you can hover to see it, and run the code action to skip it if you don't like it.

You can also tell Sourcery not to suggest all refactorings or a specific type of refactoring for a function.

  • Add a comment # sourcery skip to a function to skip all reactorings for that function
  • Add a comment # sourcery skip: <refactoring-id> to a function to skip the specific refactoring in that function. A full list of refactorings and their IDs are available at Current Refactorings.

Advanced Features

There are more advanced ways you can improve your code with a Sourcery Pro or Sourcery Team subscription:

Extract Duplicate Code Into Methods

Sourcery will automatically detect opportunities for repeated or nearly repeated sections of code within a function to be extracted out into their own methods. When these refactorings are suggested, the new methods will be given a generic name based on the function it was extracted from and you can easily rename it.

Configuring Sourcery

See our section on Configuring Sourcery for details on customizing your Sourcery configuration.

Back to top