Skip to content

Style Guide

Ruff

An extremely fast Python linter and code formatter, written in Rust.

安装 VS Code 插件 ,简单配置如下:

json
// .vscode/settings.json
{
  "[python]": {
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
      "source.fixAll": "explicit",
      "source.organizeImports": "explicit"
    },
    "editor.defaultFormatter": "charliermarsh.ruff"
  }
}

Naming

Class

py
class fooClass: ...
class foo_class: ...

class FooClass: ...

Function

py
def CapCamelCase(*a): ...
def mixCamelCase(*a): ...

def foo_bar_function(): ...

Variable

py
FooVar = "CapWords"
fooVar = "mixedCase"
Foo_Var = "CapWords_With_Underscore"

# local variable
var = "lowercase"

# internal use
_var = "_single_leading_underscore"

# avoid conflicts with Python keyword
var_ = "single_trailing_underscore_"

# a class attribute (private use in class)
__var = " __double_leading_underscore"

# "magic" objects or attributes, ex: __init__
__name__

# throwaway variable, ex: _, v = (1, 2)
_ = "throwaway"

Others

  • Modules (filenames): short, all-lowercase names, and they can contain underscores
  • Packages (directionaries): short, all-lowercase names, preferably without underscores
  • Variable names are not full descriptors
  • Put details in comments
  • Too specific name might mean too specific code
  • Keep short scopes for quick lookup
  • Spend time thinking about readability

Summary

TypePublicInternal
Packageslower_with_under
Moduleslower_with_under_lower_with_under
ClassesCapWords_CapWords
ExceptionsCapWords
Functionslower_with_under()_lower_with_under()
Global/Class ConstantsCAPS_WITH_UNDER_CAPS_WITH_UNDER
Global/Class Variableslower_with_under_lower_with_under
Instance Variableslower_with_under_lower_with_under
Method Nameslower_with_under()_lower_with_under()
Function/Method Parameterslower_with_under
Local Variableslower_with_under