Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Latest commit

 

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 

Repository files navigation

Python good practice

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

Variable

You should not mix camelCase and snake_case styles.

Use snake_case for name variable as suggested in PEP8

Variables should have short names that inform what they contains.

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

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

class Donkey:
    pass

Good

class Donkey: 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)
...

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(BaseException): pass
class NotToyException(BaseException): 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
# vim: set fileencoding=UTF-8 :

Always write file with encoding UTF-8

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

used in project

Eg.

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 80 characters

Set last in file empty

Instead print debuging use pdb module

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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors