What are you missing? ft. Python

aps08
8 min readJul 24, 2022

Are you learning python? Does your development activity revolves around python? Are you confused, what to add and what to not, to make your code more professional?

Python logo with questions revolving around it.

If YES, then this article is for you. In this article I will be going through some (1) Modules, (2) tip and tricks and (3) good practices which you might like to add in your code.

keywords — python, black, isort, pylint, module, package, logging, typing, lambda and comprehensions.

Modules

1. Logging

logging which simply means to keep track of all the event during code execution. It is very important for software development, as it helps us debugging the problem. In a large application, where you don’t have a logger, there are very high chances, that you won’t be able to find the point of failure.

That’s why, python comes with a standard module called “logging”, which could be used for this purpose. Let’s see an example:

logging example

In the above example, you see only warning, critical and error messages, as the it’s the default setting. logging module gives you flexibility, you can log different level of messages either on console, or store the logs in a log file, you can change the format of the message. Storing the log in a file gives you more advantage, as you can see the log whenever you want. You can read more about the module here.

2. Typing

Since python is a dynamically typed language, it is optional to define the data type of a variable, but some times it might make things hard for us. To understand the problem let’s see a example code:

Problem with no type hint

In the above example, first code run printed “Even”, which is fine, but for the second code run, it’s showing a “TypeError”, as the function need a integer in the parameter “n”, but we passed a string. In simple words, the function doesn’t tell us what kind of value the function is expecting.

In a large code base, where we have many functions, it’s not possible to read all the functions and guess the type of value the function is expecting, it always a good practice to add type hint in function definition, so other developers who are reading the code can conclude what’s the data type of the parameter which are present in the function definition. Let’s see the same example again with type hint:

Type hint

In the above example, we can conclude just by reading the first line of the function definition, that it’s expecting an integer. Also “ — >None” mentioned at the end of first line in the function, signifies that this function returns nothing.

Python also has typing module, which provides runtime support for type hints. You can also create alias for big custom data type, and even new datatypes using this module. Any, Union, Callable, TypeVar and Generic are the most fundamental support.

Dataclasses

Working with large code base, we might find it difficult and time taking process to create multiple classes now and then. With “dataclasses” module, we can easily create the classes using decorators, and structure the classes and add fields in dunder methods by passing configuration all together or field by field. Let’s take a quick look on a code example, where we are creating a student class:

Class using dataclasses

As you can see in the above example, using dataclass decorator, we have created a class in just 5 lines, and using init, and repr parameter, we have configured the class to create “__init__”and “__repr__” dunder method automatically. In case of normal classes, we need to create these dunder function explicitly. You can also add or remove members of a class from a dunder method by using the field function.

Tips and Tricks

Black

While looking into large project in our offices or on GitHub, we wonder, how the engineers manage to format the code so well ? It’s easy to read, and looks professional. The answer to that question is that, “they don’t do it”. There are many external python packages which can format your code easily, and one of the best is “black”. By installing black, you agree to cede control over minutiae of hand-formatting. In return, Black gives you speed, determinism, and freedom from “pycodestyle” nagging about formatting. Use “pip install black” to install it. Let’s see an example:

Unformatted code

As you can see in the above code, there is a empty line between the dictionary declared, no gap between the function definition and call. And similar for formatting mistakes. Now, save and close this code as sample.py and run the command “black sample.py” in terminal/cmd. Re-open the sample.py file and your code will be formatted, as given in the below image. It only changes the formatting of the code, and doesn’t change the places of the code.

formatted code

Isort

Just like a large project, we might some times require large number of import in our scripts from internal, external and custom libraries. And we must arrange the import statement according python guidelines. But just like black, we have another package named “isort” to automate this process. You can install by running “pip install isort”. Let’s look at an example:

Unsorted imports

Type the code given in the above image, now save the file as sample.py and close it, now in the terminal/cmd run the command “isort sample.py”. After running the command. You will will see the output as given in the below image. (Please keep in mind, that helper is my custom module, which you might not have)

sorted import

Pylint

Till now, we have discussed about formatting the code, now how do we know, if we are following all the coding standards or not? How do we get to know, if we have used the type hinting, missed the doc string or something in our code? Just like black and isort, which are used for formatting the code, we have pylint, which analyses and warns us about errors and enforces a coding standard. It doesn’t make any changes in the code, but warns us about the lines, which don’t meet the standards. It also scores our code out of 10.

You can install pylint by running “pip install pylint” on terminal/cmd. Let’s look at an example code, in this example we writing a rough code and later we will run pylint on it to check for errors:

Rough code

Now, save this file as sample.py, and run pylint on it by running the command “pylint sample.py” on terminal/cmd. You will receive the follow output in the terminal/cmd.

Result after running pylint

My code scored 4.29, which is really bad😭😭😭. But, we have got all the warning, along with line number so, we can rectify it. Let’s make some changes in the code and run pylint again. After making changes in the code. Our code looks like this.

Resolved all pylint warnings

Now, after re-running the pylint again on this code. We get the following result.

Finally, after making the appropriate changes, mentioned by pylint, we are able to reach a 10/10 score. So, basically pylint will help you keep your coding standard as per mark, if you follow and clear all the warning mentioned by it.

Good Practices

List comprehensions

Let’s say we have to create a list of n numbers, most people follow the approach given in the below image, which takes more space in our code:

Created list without list comprehension

It’s better to use list comprehension, it’s a way to define and create list in python one-liner code, you can also use this with dictionary, and we can also add if condition as per need. The code in the above image can also be written as given below:

Created list with list comprehension

Lambda

A lot of time, we have to create small function, which don’t perform much operation, this is where lambda comes into picture. Lambdas are just anonymous function, which can take n number of argument, but can only return one expression.

Let’s say we have to create a function, which takes age( integer), balance( integer) and time to retirement(in integer in years), and return the balance of the customer at the time of retirement. So, we will be implementing it using lambda function, since it’s only returning once mathematical calculation.

Created lambda function

Map

Many time, we have to pass values from an iterator to a function, and I have seen most people for loop for this, which is not a good practice, as we already have a function called Map, which helps us map a iterator object with a function, and returns an iterable object, which can be casted to list to print. Let’s take an example, we have to pass 10 number in a function to check which is even and which is odd.

Calling a function multiple times using map

Thank you all, for such an awesome response on my last 3 article. We have crossed 1.5K views. 😃😃😃 . If you like this article give me a clap and feel free to connect with me on Twitter, GitHub and LinkedIn.

My old articles:

  1. Python Design Pattern- Behavioral | Part 3 [Technical]
  2. Python Design Pattern- Structural| Part 2 [Technical]
  3. Python Design Pattern- Creational | Part 1[Technical]

--

--