Skip to content

PEP8_python_code_structure_template

Maarten edited this page Mar 12, 2021 · 1 revision
''' AN OVERVIEW:

IMPORTS
	builtint libraries
	3th party libraries
	local libraries
CONSTANTS
CLASSES
FUNCTIONS
OTHER CODE

'''

## IMPORTS

# Start with builtin python libraries
import sys # All libraries go on a single single
import os
from os import mkdir, path # You can import submodules on the same line

# After builtins come 3th party libraries (the ones you install with pip)
import numpy as np
import matplotlib.pyplot as plt

# Finally, import the local libraries, i.e. libraries you've written yourself
from some_second_file import your_own_function

## CONSTANTS
'''
Constants are used for variables that do NOT change.
Constants are always uppercase
By setting constants, these values, often used throughout the code,
can clearly be named, as LINE_NOISE_FS is much easier to understand
than a seemingly random number like 50
It's also a much better solution than using 'global some_var', which
is very error prone
''' 

LINE_NOISE_FS = 50
FIGURE_SIZE = (16, 8)

## CLASSES

class your_class(inherited_parent_class):
	# One line between methods (remember that a function within a class is a method)
	def __init__(self):
		pass

	def some_method(self):
		pass
					# two lines
					# between and after classes

class your_second_class(inherited_parent_class):

	class_constant = 1 # Class constants go here

	def __init__(self):
		pass
					# again, double
					# space after a class
def your_function(input_one, input_two=some_value):

	# See how I immidiately know why this line is here by using a well named constant?
	filtered_data = some_notch_filter(input_one, frequency_to_remove=LINE_NOISE_FS)  

def your_next_function(var_1,
					   keyword_arg_1=1,
					   keyword_arg_2=2):
	# If you have many function arguments,
	# considered lining them up
	return some_value
					# Two lines
					# after sections with functions

if __name__ == '__main__':
	'''using __name__ == '__main__' is good practice,
	   but might be unnecessary for the code we 
	   write. Its used so the code withing the
	   if function isn't run when you import this
	   file in another script. It will run when
	   you run this script'''
	your_function()
	your_next_function()
Clone this wiki locally