Skip to content

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

1 watching

Forks

Latest commit

 

History

20 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 

Repository files navigation

Python good practices

This document show how to write readable source code in Python.

Shebang

Always start main python file with correct shebang

#!/usr/bin/env python3

Module level dunders

Always write module level dunders

Before dunders use only imports from future

Other import should be after dunders

#!/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 imports

Variable

You should not mix camelCase and snake_case styles.

Use snake_case for name variable as suggested in PEP8

Variable names should be written in lowercase.

Variables should have short names that inform what they contains.

Write code in English language and avoid UTF8 chars.

Very very bad

My_String = "Temporary value"

Very bad

MyString = "Temporary value"

Bad

This_is_my_string_variable = "Author: Draqun"

Good

author_info = "Author: Draqun"

Using variable type in name is wrong!

Bad

my_string = "Temporary value"

Good

tmp = "Temporary value"

If variable need always some value use only if statement

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_variable

IF you create variable and it contains one object do not use plural version in names

Bad

donuts = Dessert()

Good

donut = Dessert()

If statement

Avoid comparison with True and False

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:
    ...

Group expression using parentheses

Bad

if len(groups) == 9 and cities and len(cities) == 7 and "Warsaw" in cities:
    pass

Good

if (len(groups) == 9) and cities and (len(cities) == 7) and ("Warsaw" in cities):
    pass

Class

CamelCase is better for class names than snake_case.

Class name should start with capital letter.

Very 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):
        ...

If class is empty create one-line class

Bad If there is no docstring

class Donkey:
    pass

Good

class Donkey: pass

or

class Donkey:
    """This is Donkey which eat grass"""
    pass

The names of the classes should be written in singular if they are not containers.

If you want add horses to your application create class for single entity.

Bad

class Horses:
  """ This is horse class """
    pass

Good

class Horse:
  """ This is horse class """
    pass

If you want create container class use plural names

Bad

class HorsesConatiner:
    """ Horses container """
    pass

Good

class Horses:
    """ Horses container """
    pass

Always set default values of class variables

Very 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 = name

Good

class Horse:
    def __init__(self, name="Adolfo"):
        self.name = name

Use 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 variable

Use the same rule to methods

class Dog(Animal):
    def bark(self): # Public method
        ...

    def _owners_name(self): # Protected method
        ...

    def __vaccination_card_number(self): # Private method
        ...

Function and methods

Use snake_case for function name and methods.

Bad

def canWriteToFile(fileHandler):
    ...

Good

def can_write_to_file(file_handler):
    ...

Use *args and **kwargs to pass arguments for nested (wrapped) function

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")

Lists, tuples and dictionaries

Use tuples when quantity is constant.

possible_names = ("John", "Joe", "Katherina")

Use list in other cases.

tastes = ["ugly", "cherry", "strawberry"]

Use dictionary when you have key-value pairs

cities_population = {"Moscow": "1 MLN", "Warsaw": "1.5 MLN"}

Operators

Use in operator to check element is in container

Good

if "Warsaw" in cities:
    pass

Use not in to ckeck element is not in container

Good

if "Warsaw" not in cities:
    pass

Avoid negation of in and not in operators

Bad

if not "Warsaw" in cities:
    pass

Bad

if not "Warsaw" not in cities:
    pass

in keyword can be used with dictionary to check element exists in collection as a key

cities_population = {"Moscow": "1 MLN", "Warsaw": "1.5 MLN"}
if "Warsow" in cities_population:
    pass

Sets

If you want check some value is in a big group use sets instead lists or tuples

Bad

cities = ["Warsaw", "Berlin", "Moscow", "New York", "London", "Madrit", ...]

if city in cities:
    pass

Good

cities = set(["Warsaw", "Berlin", "Moscow", "New York", "London", "Madrit", ...])

if city in cities:
    pass

Use duck typing if class are not exceptions

Duck typing idea

Bad

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():
        ...

Use inheritance when you create exceptions tree

class NotAnimalException(Exception): pass
class NotToyException(Exception): pass
class NotMyLittlePonyToyException(NotToyException): pass
class NotHamsterException(NotAnimalException): pass

Exceptions

Use try except block only for part of code which raises exceptions

Bad

def send_message(message):
    ... # some action before try except
    try:
        message_striped = message.strip()
        ... # Some action for sending
    except AttributeError:
        ... # Some error handling

Good

def send_message(message):
    ... # some action before try except
    try:
        message_striped = message.strip()
    except AttributeError:
        ... # Some error handling
    else:
        ... # Some action for sending

Other

Always on top file put info about interpreter and encoding

For Python 2 and emacs encoding

#!/usr/bin/env python2.7
#-*- coding:utf-8 -*-

or Python 3 and vim encoding

#!/usr/bin/env python3

Always write file with encoding UTF-8

Always create file requirements.txt and put there names and version library

used in project

Eg.

mypy==0.961
pylint==2.15.10
Django==1.8.2
wheel==0.26.0

Create every class in own file

Create modules for group of class

Use init files for expose public class and for hidding internal modules

Do not write code line longer than 100(or 120 for wide displays) characters

Set last in file empty

Instead print debuging use pdb module

Instead print use logging module for logs

Use pylint and/or mypy for static analysis

If you want more go to https://www.python.org/dev/peps/

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors