DEV Community

Cover image for Best python programming practices - Every Python Developer Must Know
Emma Donery
Emma Donery

Posted on

Best python programming practices - Every Python Developer Must Know

1. Create a Code Repository and Implement Version Control

A regular project’s structure looks like this:

- docs/conf.py

The configuration directory

- docs/index.rst

This is the index file for the documentation, or what lives at / . It can be thought of as a landing page that contains child topics for users to navigate to.

- module/_init_.py

The _init_.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.

- module/core.py

holds the base level classes

- tests/core.py

Most projects have tests- keep these in the tests directory. It is documented for the benefit of the core developers of Python

- LICENSE

This is in the root directory and is where you should add a license for your project.

- README.rst

This is in the root directory and is where you describe your project and what it does.

- requirements.txt

This is not mandatory, but if you use this, you put it in the root directory. This requirements.txt file is used for specifying what python packages are required to run the project you are looking at.

- setup.py

This script in the root lets distutils build and distribute modules needed by the project.

2. Create Readable Documentation

Readability is a primary focus for Python developers, in both project and code documentation
For this, you can use Markdown, reStructuredText, Sphinx, or docstrings.

- Markdown and reStructuredText are markup languages with plain text formatting syntax to make it easier to mark up text and convert it to a format like HTML or PDF.

- reStructuredText lets you create in-line documentation.Most Python documentation is written with reStructuredText. It’s like Markdown, but with all the optional extensions built in.

- Sphinx is a tool to easily create intelligent and beautiful documentation.
Sphinx is far and away the most popular Python documentation tool. It converts reStructuredText markup language into a range of output formats including HTML, LaTeX (for printable PDF versions), manual pages, and plain text.
There is also great, free hosting for your Sphinx docs. You can configure it with commit hooks to your source repository so that rebuilding your documentation will happen automatically.
When run, Sphinx will import your code and using Python’s introspection features it will extract all function, method, and class signatures. It will also extract the accompanying docstrings, and compile it all into well structured and easily readable documentation for your project.
Sphinx is famous for its API generation, but it also works well for general project documentation. learn more about sphinx here

- Docstrings are documentation strings at the beginning of each module, class, or method.
Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.
Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or ”’”’triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.
Accessing Docstrings*: The docstrings can be accessed using the doc method of the object or using the help function.

def my_function():
#Declaring Docstrings
    '''Demonstrates triple double quotes
    docstrings and does nothing really.''' 

    return None
#Accessing Docstrings  
print("Using __doc__:")
print(my_function.__doc__)

#Accessing Docstrings  
print("Using help:")
help(my_function)
Enter fullscreen mode Exit fullscreen mode
output:
Using __doc__:
Demonstrates triple double quotes
    docstrings and does nothing really.
Using help:
Help on function my_function in module __main__:

my_function()
    Demonstrates triple double quotes
    docstrings and does nothing really.
Enter fullscreen mode Exit fullscreen mode

3. Follow Style Guidelines

PEP stands for Python Enhancement Proposals- these are guidelines and standards for development. This is to make sure all Python code looks and feels the same.
Such guidelines include:
a) To name classes with the CapWords convention.
b) Use proper naming conventions for variables, functions, methods, and more.
c) Variables, functions, methods, packages, modules: this_is_a_variable
d) Classes and exceptions: CapWords
e) Protected methods and internal functions: _single_leading_underscore
d) Private methods: __double_leading_underscore
e) Constants: CAPS_WITH_UNDERSCORES
f) Use 4 spaces for indentation.
For more conventions, refer to PEP8.

4. Correct Broken Code Immediately

Like with the broken code theory, correct your broken code immediately. If you let it be while you work on something else, it can lead to worse problems later.
This is what Microsoft does. It once had a terrible production cycle with MS Word’s first version.
So now, it follows a ‘zero defects methodology’, and always corrects bugs and defects before proceeding.

5. Use the PyPI Instead of Doing it Yourself

The Python Package Index (PyPI) is a repository of software for the Python programming language.
It helps you find and install software developed and shared by the Python community.
It has more than 198,190 projects at the time of writing.
You should use code from this instead of writing it yourself- this saves time and lets you focus on the more important things.
Install these using pip. You can also create and upload your own package here.

6. The Zen of Python

Tim Peters wrote this short poem to express what values you should follow while coding in Python.
You can get this by running “import this” in the IDLE.

import this
Enter fullscreen mode Exit fullscreen mode
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!
Enter fullscreen mode Exit fullscreen mode

7. Use the Right Data Structures

Data structures are the fundamental constructs around which you build your programs. Each data structure provides a particular way of organizing data so it can be accessed efficiently, depending on your use case.
Know the benefits and limitations of different data structures, and choose the right one while Coding in Python.

8. Write Readable Code

  • You should use line breaks and indent your code.
  • Use naming conventions for identifiers- this makes it easier to understand the code.
  • Use comments, and whitespaces around operators and assignments.
  • Keep the maximum line length 79 characters.

9. Use Virtual Environments

The main purpose of Python virtual environments is to create an isolated environment for Python projects. This means that each project can have its own dependencies, regardless of what dependencies every other project has.
You should create a virtual environment for each project you create.
This will avoid any library clashes, since different projects may need different versions of a certain library.

#Installing virtualenv
pip install virtualenv
#Test your installation
virtualenv --version
#creating virtualenv
virtualenv virtualenv_name
#activating virtualenvironment
source virtualenv_name/bin/activate #mac and linux
Enter fullscreen mode Exit fullscreen mode

10. Write Object-Oriented Code

Python is an object-oriented language, and everything in Python is an object. You should use the object-oriented paradigm if writing code for Python.
This has the advantages of data hiding and modularity. It allows reusability, modularity, polymorphism, data encapsulation, and inheritance.

11. What Not to Do while Programming in Python

  • Avoid importing everything from a package- this pollutes the global namespace and can cause clashes.
  • Don’t implement best practices from other languages.
  • Do not turn off error reporting during development- turn it off after it.
  • Don’t alter sys.path, use distutils for that.

Top comments (2)

Collapse
 
zkabwang profile image
Zkabwang

Thank you for sharing

Collapse
 
emma_donery profile image
Emma Donery

pleasure