This document show how to write readable source code in Python.
#!/usr/bin/env python3#!/usr/bin/env python3
from __future__ import * # Before dunders use only imports from future
__all__ = ["a", "b"] # All data which can be imported from module
__version__ = '1.0'
__author__ = 'John Smith'
__email__ = '[email protected]'
__copyright___ = "Copyright (c) 2018 John Smith"
import sys # Other importsVery very bad
My_String = "Temporary value"Very bad
MyString = "Temporary value"Bad
This_is_my_string_variable = "Author: Draqun"Good
author_info = "Author: Draqun"Bad
my_string = "Temporary value"Good
tmp = "Temporary value"Very Bad
def func(some_value):
if some_example_function(some_value):
variable = another_variable
else:
variable = "Default Value"Not Bad
def func(some_value):
variable = another_variable if some_example_function(some_value): else "Default Value"Good
def func(some_value):
variable = "Default Value"
if some_example_function(some_value):
variable = another_variableBad
donuts = Dessert()Good
donut = Dessert()Bad
is_pony = True
...
if is_pony == True:
...or
is_hungry = False
...
if is_hungry == False:
...Good
is_pony = True
...
if is_pony:
...or
is_hungry = False
...
if not is_hungry:
...Bad
if len(groups) == 9 and cities and len(cities) == 7 and "Warsaw" in cities:
passGood
if (len(groups) == 9) and cities and (len(cities) == 7) and ("Warsaw" in cities):
passVery Bad
class My_little_Pony:
def run_pony(self):
...Bad
class my_little_pony:
def run_pony(self):
...Good
class MyLittlePony:
def run_pony(self):
...Bad If there is no docstring
class Donkey:
passGood
class Donkey: passor
class Donkey:
"""This is Donkey which eat grass"""
passIf you want add horses to your application create class for single entity.
Bad
class Horses:
""" This is horse class """
passGood
class Horse:
""" This is horse class """
passIf you want create container class use plural names
Bad
class HorsesConatiner:
""" Horses container """
passGood
class Horses:
""" Horses container """
passVery bad
class Horse:
name = "Adolfo"Bad
class Horse:
def __init__(self, name):
if (name):
self.name = name
else:
self.name = "Adolfo"or
class Horse:
name = "Adolfo"
def __init__(self, name):
if(name):
self.name = nameGood
class Horse:
def __init__(self, name="Adolfo"):
self.name = nameUse single underscore as prefix of protected variable and double underscore as prefix of private variable.
class Horse:
def __init__(self):
self.name = "Rafaello" # Public variable
self._stud = "Warsaw" # Protected variable
self.__medal_winner = False # Private variableclass Dog(Animal):
def bark(self): # Public method
...
def _owners_name(self): # Protected method
...
def __vaccination_card_number(self): # Private method
...Bad
def canWriteToFile(fileHandler):
...Good
def can_write_to_file(file_handler):
...Bad
def path_is_correct(path):
...
return path
def create_relative_path_for_file(filename, path):
path = path_is_correct(path)
...
...
create_relative_path_for_file("shadow", "/etc")Good
def path_is_correct(path):
...
return path
def create_relative_path_for_file(filename, *args, **kwargs):
path = path_is_correct(*args, **kwargs)
...
...
create_relative_path_for_file("shadow", "/etc")possible_names = ("John", "Joe", "Katherina")tastes = ["ugly", "cherry", "strawberry"]cities_population = {"Moscow": "1 MLN", "Warsaw": "1.5 MLN"}Good
if "Warsaw" in cities:
passGood
if "Warsaw" not in cities:
passBad
if not "Warsaw" in cities:
passBad
if not "Warsaw" not in cities:
passcities_population = {"Moscow": "1 MLN", "Warsaw": "1.5 MLN"}
if "Warsow" in cities_population:
passBad
cities = ["Warsaw", "Berlin", "Moscow", "New York", "London", "Madrit", ...]
if city in cities:
passGood
cities = set(["Warsaw", "Berlin", "Moscow", "New York", "London", "Madrit", ...])
if city in cities:
passBad
class Animal: pass
class Horse(Animal):
def get_noise():
...
class Duck(Animal):
def get_noise():
...Good
class Horse:
def get_noise():
...
class Duck:
def get_noise():
...class NotAnimalException(Exception): pass
class NotToyException(Exception): pass
class NotMyLittlePonyToyException(NotToyException): pass
class NotHamsterException(NotAnimalException): passBad
def send_message(message):
... # some action before try except
try:
message_striped = message.strip()
... # Some action for sending
except AttributeError:
... # Some error handlingGood
def send_message(message):
... # some action before try except
try:
message_striped = message.strip()
except AttributeError:
... # Some error handling
else:
... # Some action for sendingFor Python 2 and emacs encoding
#!/usr/bin/env python2.7
#-*- coding:utf-8 -*-or Python 3 and vim encoding
#!/usr/bin/env python3used in project
Eg.
mypy==0.961
pylint==2.15.10
Django==1.8.2
wheel==0.26.0
