Style Guide/Python

Python Style Guide

Python code should adhere to PEP 8, with the following clarifications:

  • Only use four spaces for indentation, no tabs.
  • Spaces around operators (except for keyword arguments).
  • Use CamelCase for classes and exception types. Use underscore_case for everything else.

Scripts with the following comment are meant to be pep8.

# <pep8 compliant>

Additions to PEP 8


  • Avoid shadowing names of Python built-in functions, constants, types, and exceptions. Instead of using object, use obj; as for other names, the Python built-ins are very generic, so often it is better to be more specific in your naming. For example, instead of naming a list list, name it objects_to_export. Not only does this avoid shadowing a built-in name, it also is more explicit and emphasises the contents of the list. If you want to make the type of the variable explicit, use type annotations.
  • Avoid overly short names. Use mesh and curve instead of me and cu (or worse, m and c).

Unused Variables & Arguments

It's sometimes necessary to declare variables or arguments that aren't used, in this case it's a common convention to begin the variable with an underscore.

Tools such as pylint will skip them when reporting unused variables.

For example, a menu's draw method always takes a context argument, which you don't necessarily need.

class EXAMPLE_MT_menu(Menu):
    bl_label = ""

    def draw(self, _context):
        layout = self.layout"EXAMPLE_MT_submenu_a")"EXAMPLE_MT_submenu_b")

Or when iterating over a sequence some items may not be used.

for (vert, _edge, face) in elements:
    process(vert, face)

Exceptions to PEP 8

  • Line width:
    Maximum width for lines is 120 for all scripts.
    Optionally you can use shorter line width, using the comment:
    # <pep8-80 compliant>
  • Imports:
    We often put imports within functions body which is not pep8 compliant.
    This is done to speed up Blender's startup times to avoid loading in many files and libraries which the user may never access.

Related Topics