Many developers or students write code, a lot of code, but sometimes they forget to follow some good practices that can make the written code more efficient and readable. There are some good practices to follow during programming. It's not just for Python developers, is applicable for every programming language like C ++, Java, C #, etc. Then, in this article, we will look at some of those overlooked but interesting and important practices to keep in mind while programming.
Source: Google images
Look at the picture above. I know it's pretty funny. But the point I want to make here is that Python is that cool. Python programmers can effortlessly accomplish a task, while others have to sweat a lot from the same task. Therefore, for python developers, it is important to follow some practices that will make your work even more productive.
Then let's get started.
1. Adequate documentation and feedback
This is the first and most important point I want to make to be a good Python developer. It is very important to follow this. Any code you are writing should be well documented and commented on by you whenever necessary. But, Do you know why we need the code documentation? The answer is very simple. A business project can last for years and years. New developers join the project at any time, so now they need to know and understand what is in the code, para este propósito la documentación del código es importante. Simplemente pueden consultarlo y comprenderán claramente el código. Solo piense en ese desarrollador si no hubiera documentación y simplemente lo arrojara al grupo de código. Es realmente difícil para él sin esto. Los comentarios también tienen el mismo propósito, debe agregar comentarios en su código donde sea necesario.
Source: Google images
Existen principalmente tres tipos de comentarios:
a. Comentario de una sola línea: Comienzan con el símbolo de hashtag (#) y duran hasta el final de la línea.
Example:
#This is a comment
#Printing Hello World!
print("Hello World!")
B. Comentario de varias líneas: Es un texto encerrado en un delimitador. (""")
en cada extremo del comentario. No debe haber espacios en blanco entre el delimitador (""")
. Se utilizan cuando el texto del comentario tiene más de una línea.
Example:
""" This is a multi line comment, spanning over three lines. This is how it's done. """ print("Sum of two numbers:", 45+23)
C. Comentarios de Docstring: Es una característica incorporada de
Piton. Se utiliza para asociar documentación que se ha escrito con módulos, functions, clases y métodos de Python. Se usa solo
debajo de las funciones, modules, clases para decir lo que están haciendo. El comentario de la cadena de documentos está disponible mediante el atributo __doc__.
Example:
def add(a, b): return a+b print(add.__doc__)
Production:
Add the two numbers a and b
Therefore, use cualquiera de estos comentarios y ayude a otros desarrolladores a saber lo que ha hecho.
2. Evite la creación de variables globales
Las variables globales son aquellas que permanecen en la aplicación hasta el último suspiro, namely, until the application runs, exist in code space and can be invoked anytime from anywhere. They are sometimes useful because of their accessibility, but at the same time, this proves to be a disaster for developers. Due to these variables, memory cannot be used efficiently either, because a large part of your memory will go permanently to these global variables.
There is one more problem with them. Since every function in your application can access global variables, it is very difficult to identify which function is reading or writing the value of those global variables. Now, to identify this, you need to take a closer look at all functions individually, which is a headache.
Therefore, avoid these global variables.
3. Exceptions handling
Source: Google images
This is a very important practice for developers to follow., not just python developers, but also all the developers of each and every one of the languages. Then, let me tell you the reasons why it is necessary. Suppose you wrote a program to open a text file and perform certain operations on it, how to read the file, close it, find file length. This would be a simple code to write, but what if errors like these occurred during execution?
- What if the file cannot be opened?
- What if the file length cannot be determined?
- What if the reading fails?
- What if the file cannot be closed?
What if the program throws these errors? Your code will stop and your application will not work. Then, these are potential errors that can occur for any reason. Therefore, it is important to handle these exceptions rather than ignoring them. Therefore, it is imperative to use exception handling in your code.
Example:
try: print(Y) except: print("An exception occurred in your code!")
the try
block will raise an exception, why y
It is not defined.
4. Create separate environments
Python programmers often try to work in a single environment, they don't create a separate environment for different projects. It is not strictly a good practice to implement all projects in one environment because you may face some problems in the later stages of development, then you need to change some facilities, modify their versions, install new. This can affect previous projects that might not accept these new changes as they depended on these dependencies. Therefore, always prefer to use a new environment.
Source: Google images
Virtualenv installation
$ pip install virtualenv
Test your installation:
$ virtualenv --version
Using virtualenv
$ virtualenv my_name
Now, once you have created your virtual environment, must activate it. Then, for that use this command:
$ source virtualenv_name/bin/activate
When your work is complete in that environment, close it with this command:
(virtualenv_name)$ deactivate
5. Use built-in features
Use built-in Python functions instead of writing them from scratch, because they are already compiled, optimized for efficient execution and if you are writing them from scratch, a great advantage is being lost.
6. Project structuring
Project structuring is also a very important part of development because it shows how efficiently you are going to write your code., how the whole project fits together. Then, if your project has a front-end, back-end, database part, API and other things and if you haven't managed all this, then it will be a very complicated project. Suppose later you want to make some changes to your code, but he won't be able to do it, because there is no structure in your code and now it's a real hassle to find what is and where.
Source: Google images
Then, to structure your project there is an interesting tool called cookie cutter. Helps you create the complete project structure, so try using this. It is a command line utility tool that creates projects from cookie cutter (draft
templates). For instance, create a Python package project from a Python package project
template.
GitHub link: https://github.com/cookiecutter/cookiecutter
Documentation: https://cookiecutter.readthedocs.io
7. Reviews (2)
I hope you read this quote:
Alone we can do so little; together we can do a lot.
This is also applicable in the world of programming. Try to give reviews about other people's code and also be open to the opinions of others. It is a good way to learn and grow, learning speed magically increases. Then, try to do this.
Source: Google images
Final notes:
These are some very good practices that every student or developer should follow. They are sure to help you in your career as a programmer. I hope you find the tips in this article helpful. Let's connect Linkedin.
Thanks for reading if you got here :).
The media shown in this article is not the property of DataPeaker and is used at the author's discretion.