PEP-8 in Python
The PEP-8 coding standard is a widely adopted set of guidelines for writing and formatting Python code.
These set of conventions help maintain consistency and uniformity within the Python community.
These conventions makes python code more easier to read.
1. Naming convention:
Variables: Besides giving a variable a good, unambiguous name that conveys its purpose at a glance, it is encouraged to use lowercase for variable names. Underscore(_) can be using when join multiple names.
e.g: email, account_balance, matric_no, user_id, total_score.
Functions: Just like variable names, functions should be lowercase. multiple words can be separated using underscore(_):
e.g. compute_discount, get_user_email. What really maters is the readability. For instance in Django(Python Web Framework), there is a function called get_object_or_404. Do you notice the readability and simplicity in this name? Even at first glance you already know what it does? Get an object or return 404(Not found) error if the object cannot be found. What an interesting name! Function name a lot of time describe an action.
Class:Class name style should follow CamelCase. What that means is that the First Letter in every word should bVe in Capital
e.g. ModelSerializer, MyClass, CustomAuthentication, ViewSets, etc.
Constant: Constant are variables that should not change in value. Use an uppercase letter and underscore(_) to separate multiple words. e.g
CONSTANT, AWS_KEY, SECRET_KEY, etc.
Method :method name should be lowercase word like function. Use underscore(_) to seperate multiple words. e.g get_name, get_age, etc.
2. Layout/Formatting:
Indentation: Indentation(leading white space) is important in Python because it is used to group a block of code. Some languages(e.g. JavaScript, Java) make use of curly brackets {} to indicate a block of code. See below a function declaration in Python and JavaScript
[*]Python relies on indentation
def my_function():
print("From Python")
[*]Javascript relies on {}
function my_function{
console.log("From JavaScript")
}
Four consecutive spaces is recommended to be used as indentation
Docstring: Documentation appears in the immediate line that follows a class, function, method, etc. It is recommended to use double string “”” or single ‘’’ while writing the doc.
e.g.
def my_function():
'''This function does this and that.... '''
pass
Line: Limit all lines to a maximum of 79 characters.
Black is a popular auto formatter for Python that’s supported by many code editors and IDEs. I am interested in learning about other formatters you use.
Thanks for reading