Blue Style Guide for Julia

repository·master·Indexed 19 days ago

https://github.com/juliadiff/bluestyle

A style guide for Julia code that synthesizes conventions from PEP8, the official Julia Style Guide, and Julia's Notes for Contributors. It provides detailed guidelines on indentation, naming conventions, module imports, function definitions, whitespace, and documentation, aiming for consistency across projects. The guide also includes configuration settings for editors such as Sublime Text, Vim, and Atom to enforce a 92-character line limit and 4-space indentation.

Tokens
3.8K
Snippets
14
Records
20
Agent score
18%

What's inside bluestyle

  1. Overview of Blue: a Style Guide for Julia

    master

    Blue is a style guide for Julia code that synthesizes conventions from PEP8, Julia's official Notes for Contributors, and the Julia Style Guide.

    Core Philosophy

    Consistency is the primary goal. While following this guide is important, consistency within a specific project or module is more important. If the guide conflicts with existing project patterns, prioritize project consistency or use your best judgment.

    Precedence

    When guidelines conflict, Blue takes precedence over the Julia Contribution Guidelines and the Julia Style Guide (unless otherwise noted).

  2. Optimize Julia performance via scoping and constants

    master

    To maximize Julia's performance through type specialization and avoid the slowness of MATLAB-style scripts, follow these two patterns:

    1. Move as much functionality as possible into functions.
    2. Declare global variables as constants using the const keyword.

    When benchmarking, avoid timing the first run of a function to account for compilation time. Instead, use the @benchmark and @btime macros from the BenchmarkTools.jl package, which handle multiple runs and provide statistical summaries.

  3. Format Whitespace and Operators

    master

    Follow these whitespace guidelines for clean Julia code:

    • Brackets/Braces: Avoid extraneous whitespace inside (), [], or {}.
    • Commas/Semicolons: Avoid whitespace before , or ;.
    • Ranges: Avoid whitespace around : in ranges (e.g., 1:9, not 1 : 9).
    • Assignments: Do not use multiple spaces to align assignment operators across lines.
    • Binary Operators: Surround operators like =, +=, ==, <, >, !=, and -> with a single space.
    • Unary Operators: Do not use whitespace between unary operands and the expression (e.g., -1, not - 1).
    • Empty Lines: Avoid extraneous empty lines. Use one empty line to separate different functions. Do not include a blank line between a function definition and its end statement.
    # Yes: No extra space in brackets
    spam(ham[1], [eggs])
    
    # Yes: Single space around binary operators
    i = j + 1
    submitted += 1
    
    # Yes: No space for unary
    -1
    
    # Yes: Proper spacing for function definitions
    function foo(bar::Int64, baz::Int64)
        return bar + baz
    end
  4. Configure VS Code for Blue style

    master

    To configure VS Code, open your settings.json (via CMD+K, CMD,+ on Mac or CTRL+K, CTRL,+ on Windows/Linux) and add the following Julia-specific settings:

    {
        "[julia]": {
            "editor.detectIndentation": false,
            "editor.insertSpaces": true,
            "editor.tabSize": 4,
            "files.insertFinalNewline": true,
            "files.trimFinalNewlines": true,
            "files.trimTrailingWhitespace": true,
            "editor.rulers": [92],
        },
    }
  5. Define Global Variables and Constants

    master
    Avoid global variables whenever possible. If required, they must be const and named using all uppercase with underscores (e.g., MY_CONSTANT). Define them at the top of the file, after imports and exports, but before any __init__ function.
  6. Format Julia testsets using a root testset

    master

    When writing tests in Julia, use the @testset macro to group tests into logical units. For packages, it is recommended to have a single "root" test set located in the runtests.jl file, which then includes other test files.

    @testset "PkgExtreme" begin
        include("arithmetic.jl")
        include("utils.jl")
    end
  7. Avoid visual noise in test comparisons

    master

    When using the @test macro, avoid adding unnecessary type information to comparisons if the values are equivalent. Since == does not strictly enforce type equality (e.g., 1.0 == 1 is true), prefer the simplest representation to reduce visual noise.

    # Yes:
    @test value == 0
    
    # No:
    @test value == 0.0
  8. Use General Type Annotations

    master

    When annotating function definitions, use the most general type possible to allow for broader input compatibility. For type fields in structs, use specific concrete types (like Int) when it is safe and optimized, but prefer parametric types if you want to allow any subtype of a specific abstract type while maintaining concrete performance.

    # Yes: General annotation
    splicer(arr::AbstractArray, step::Integer) = arr[begin:step:end]
    
    # Yes: Parametric type for performance and flexibility
    mutable struct MySubString{T<:AbstractString} <: AbstractString
        string::T
        offset::Integer
        endof::Integer
    end
  9. Configure Vim for Blue style

    master

    To configure Vim, update your ~/.vim/vimrc and create a file at ~/.vim/after/ftplugin/julia.vim with the following settings.

    " ~/.vim/vimrc
    set tabstop=4       " Set tabstops to a width of four columns.
    set softtabstop=4   " Determine the behaviour of TAB and BACKSPACE keys with expandtab.
    set shiftwidth=4    " Determine the results of >>, <<, and ==.
    
    " Identify .jl files as Julia. If using julia-vim plugin, this is redundant.
    autocmd BufRead,BufNewFile *.jl set filetype=julia
    
    " ~/.vim/after/ftplugin/julia.vim
    setlocal expandtab       " Replace tabs with spaces.
    setlocal textwidth=92    " Limit lines according to Julia's CONTRIBUTING guidelines.
    setlocal colorcolumn=+1  " Highlight first column beyond the line limit.
  10. Configure Atom for Blue style

    master

    Atom defaults to an 80-character line length. To change this to the Blue preferred 92 characters:

    1. Go to Atom -> Preferences -> Packages.
    2. Search for the language-julia package and open its settings.
    3. Find preferred line length (under Julia Grammar) and change it to 92.
  11. Configure Sublime Text for Blue style

    master

    To align Sublime Text with the Blue style guide, navigate to Preferences > Settings - More > Syntax Specific - User for Julia files and apply the following configuration:

    {
        "translate_tabs_to_spaces": true,
        "tab_size": 4,
        "trim_trailing_white_space_on_save": true,
        "ensure_newline_at_eof_on_save": true,
        "rulers": [92]
    }
  12. Format NamedTuples

    master

    In NamedTuples, use the = character with spacing similar to keyword arguments (no space between the name and value). Do not prefix the start of a NamedTuple with ;. The empty NamedTuple should be written as NamedTuple().

    # Yes
    xy = (x=1, y=2)
    x = (x=1,)
    x = (; kwargs...)
    
    # No
    xy = (x = 1, y = 2)
    xy = (;x=1,y=2)