Sitemap
Keisuke Daimon

Keisuke Daimon

Tech Unit Leader (Python, Java, AI, Scrum, AWS). LinkedIn → https://www.linkedin.com/in/keisuke-daimon

Python Coding Style Basics

3 min readNov 19, 2024

--

The most important Python coding conventions for those who are familiar with other programming languages but new to Python.

Note that “most important” is defined based on my experience and I try to make things simple. Please leave comments if you have any opinions.

Contents

  1. Names
  2. Underscores
  3. Whitespaces
  4. Lines

Basic Knowledge

In Python, functions and methods are different. Simply speaking, functions are outside of class, while methods are inside of class.

def function():  # This is a function.
return 1

class Test:
def method(self): # This is a method.
return 1

1. Names

Roughly speaking, there are only 3 patterns.

  1. Classes: PascalCase (Capitalize the first character of each word)
  2. Constants: CAPITAL_ONLY (Capitalize all characters and place one underscore between two words)
  3. Others: snake_case

Names of functions/methods and boolean type variables often start with a verb. (e.g. def fetch_sales_data, is_member).

2. Underscores

Underscores in Python have special meanings.

2–1. Private

Python does not have private variables/functions/methods, but has a rule: treat names with a leading underscore as private!

class TestClass:
public_value = 1
_private_value = 0

# This is a public value
print(TestClass.public_value)

# This is a private value, but it can be accessed. (NOT RECOMMENDED!!!)
print(TestClass._private_value)

Note that you don’t have to use a leading underscore for variables in a function because they are not accessible from outside anyway.

def test() -> None:
public_value = 1 # Just define variables in this way
_private_value = 0 # Don't use a leading underscore to make this "private"

print(test.public_value)

### RESULT ###
# AttributeError: 'function' object has no attribute 'public_value'

2–2. Unused Return Value

If a function/method returns more than one value and you don’t need all, don’t set all return values to new variables.

Get Keisuke Daimon’s stories in your inbox

Join Medium for free to get updates from this writer.

Here, underscore means “I don’t need the return value”.

def repeat(a: str, b: str) -> tuple[str, str]:
return a, b

x, _ = repeat("hello", "world") # Ignore the second return value
print(x)

2–3. Comma in number

This is actually similar to Java. You can add underscores to numbers for readability.

i = 10_000_000

3. Whitespaces

3–1. Indentation (E101, E111)

Use 4 whitespaces! Use 4 whitespaces! Use 4 whitespaces!

This is very important. Please don’t use a tab!

3–2. Whitespace After “:” (E231)

One whitespace is recommended after “:” for type hints and dictionary.

# BAD
def add_one(i:int) -> int:
return i + 1

# GOOD
def add_one(i: int) -> int:
return i + 1

# BAD
d = {'a':1, 'b':2}

# GOOD
d = {'a': 1, 'b': 2}

3–3. No Whitespace Around Keyword / Parameter Equals (E251)

This may be confusing, but use no whitespace around “=” when calling a function/method.

def test(i: int) -> int:
return i

# BAD
a = test(i = 1)

# GOOD
a = test(i=1)

3–4. No Multiple Whitespaces Around “=” (E221, E222)

If you are used to some other languages, you may add whitespaces so that all lines have the same distance from the first character to “=”. This is not recommended in Python.

# BAD
one: int = 1
two: bool = True
three: str = "STRING"

# GOOD
one: int = 1
two: bool = True
three: str = "STRING"

4. Lines

4–1. Line Length (E501)

PEP8 defines “Limit all lines to a maximum of 79 characters.” To be honest, it’s too short to code, and there will be lots of new lines.

I personally prefer 120 characters or more.

4–2. Two Blank Lines (E302, E305)

Python prefers two blank lines over one blank line in some cases. You can think between import/from … import … and “class”, between import/from … import … and “function”, and between “class” and “function”.

### BAD ###
import os

def test1():
print("Hello, World!")

def test2():
print("Goodbye, World!")


### GOOD ###
import os


def test1():
print("Hello, World!")


def test2():
print("Goodbye, World!")

Comments

Remember all of these above!
If you don’t want to do it, just use Flake8 :)

References

--

--

Written by Keisuke Daimon

Tech Unit Leader (Python, Java, AI, Scrum, AWS). LinkedIn → https://www.linkedin.com/in/keisuke-daimon