Explore Flask

2.1. Let's have a PEP rally!

A PEP is a "Python Enhancement Proposal." These proposals are indexed and hosted at python.org. In the index, PEPs are grouped into a number of categories, including meta-PEPs, which are more informational than technical. The technical PEPs, on the other hand, often describe things like improvements to Python's internals.

There are a few PEPs, like PEP 8 and PEP 257 that are meant to guide the way we write our code. PEP 8 contains coding style guidelines. PEP 257 contains guidelines for docstrings, the generally accepted method of documenting code.

2.1.1. PEP 8: Style Guide for Python Code

PEP 8 is the official style guide for Python code. I recommend that you read it and apply its recommendations to your Flask projects (and all of your other Python code). Your code will be much more approachable when it starts growing to many files with hundreds, or thousands, of lines of code. The PEP 8 recommendations are all about having more readable code. Plus, if your project is going to be open source, potential contributors will likely expect and be comfortable working on code written with PEP 8 in mind.

One particularly important recommendation is to use 4 spaces per indentation level. No real tabs. If you break this convention, it'll be a burden on you and other developers when switching between projects. That sort of inconsistency is a pain in any language, but white-space is especially important in Python, so switching between real tabs and spaces could result in any number of errors that are a hassle to debug.

2.1.2. PEP 257: Docstring Conventions

PEP 257 covers another Python standard: docstrings. You can read the definition and recommendations in the PEP itself, but here's an example to give you an idea of what a docstring looks like:

def launch_rocket():
   """Main launch sequence director.

   Locks seatbelts, initiates radio and fires engines.
   # [...]

These kinds of docstrings can be used by software such as Sphinx to generate documentation files in HTML, PDF and other formats. They also make it easier to understand your code.


  • PEP 8
  • PEP 257
  • Sphinx, the documentation generator created by the same folks who brought us Flask