If You Are A Python Programmer, Avoid These Mistakes!

Gaurav Sharma 01 Jul, 2021 • 5 min read

This article was published as a part of the Data Science Blogathon

Introduction

Python is a simple and easy-to-learn programming language. But still some programmers especially newer ones to the language get mislead. Many programmers have experience with core programming languages like Java, C++, or C#. So they are used to doing it the hard way and when they use this python language which is with easy syntax they misinterpret the diversity and power of Python and sometimes end up surrounded with errors.

 Python Mistakes

Source: Google Images

In this article, I will try to put forward those mistakes. This article can be read by any python developer who is at a basic or intermediate level. There are some very common errors like typos, python’s case sensitivity, ignoring Indentation, not using colons for compound statements. These are basic errors that almost everyone is familiar with. We will look at some more errors in detail.

So, let’s get started!

1. Modifying a list while iterating over it

This is a problem faced by almost every python programmer at least once in their coding journey.

Look at this code below:

odd = lambda x : bool(x % 2)
numbers = [n for n in range(20)]
for i in range(len(numbers)):
  if odd(numbers[i]):
      del numbers[i]              # Deleting item from a list while iterating over it

Error:

Traceback (most recent call last):
  	  File "<stdin>", line 2, in <module>
IndexError: list index out of range

This problem is obvious but still, sometimes programmers do this. So, the solution to this problem is to use list comprehensions. They are very useful in this kind of situation.

By using list comprehension:

odd = lambda x : bool(x % 2)
numbers = [n for n in range(20)]
numbers[:] = [n for n in numbers if not odd(n)]
print(numbers)

Output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

2. Misuse of expressions as defaults for function arguments

This is one of those errors which are hard to debug because it does not give any error and works fine in almost all cases. But this can cause you trouble in complex workspaces.  When we specify a mutable optional function argument this error occurs. Look at the code below to understand better.

def myFunc(myArr=[]):
  myArr.append("Hello")
  return myArr

This is a simple function that would append “Hello” at the end of the list given to it otherwise it will return [“Hello”] whenever it is invoked without myArr argument. But we get something else, look at it:

Output:

>>>myFunc()
["Hello"]
>>>myFunc()
["Hello", "Hello"]
>>>myFunc()
["Hello", "Hello", "Hello"]

I hope you got it, this is not the output we were expecting. But since this piece of code doesn’t give any error most of the developers could get away with this if not noticed. Let’s understand this.

In python, the default arguments are evaluated only once. On the first call, it worked fine but on the next calls (second, third) it used the existing myArr instead of initializing it again. So, to solve this:

def myFunc(myArr=None):
  if myArr is None:
    myArr=[]
  myArr.append("Hello")
  return myArr

Output:

>>>myFunc()
["Hello"]
>>>myFunc()
["Hello"]

3. Class variables used incorrectly

Let’s look at this example:

class temp1(obj):
    t=5
class temp2(temp1):
    pass
class temp3(temp1):
    pass
print( temp1.t, temp2.t, temp3.t)

Output

5
5
5

This looks good.

Now if,

temp2.t = 2
print( temp1.t, temp2.t, temp3.t)

Output

5
2
5

This is also fine.

Now if I change the value of class temp1 look what happens:

temp1.t = 3
print( temp1.t, temp2.t, temp3.t)

Output

3
2
3

Boom! Value of class temp3 also changed. But this is not what we wanted. In python, the class variable is internally handled as dictionaries and follows an order known as Method Resolution Order. This happened because variable t was not present in class temp3 so it was looked up in the base class which is temp1. Hence we got this output.

4. Often trying to reinvent the wheel

Programmers coming from low-level language backgrounds like C++, C, etc. try to write everything from scratch. You might be aware that the python community is quite large, here every problem has a solution(seriously). Here we are discussing basic things that python offers. Some of those are related to using of decorators, generators, sort functions, etc. People often write custom sort function which is not needed. It just makes your code length and messy. To make your code more elegant use this:

list.sort(key = , reverse = )

We can sort tuples, dictionaries, or any python object with this. So, it can be used in almost every scenario. Look at these examples:

numbers = [4,5,2,18,3]
numbers.sort(reverse=True)
print("Sorted numbers in Decreasing order:", numbers)

Output:

Sorted numbers in Decreasing order: [18, 5, 4, 3, 2]

With a list of tuples:

#take second element for sort
def second(elem):
    return elem[1]

#random list
myList = [('a', 2), ('r', 4), ('t', 1), ('g', 3)]

# sort list with key
myList.sort(key=second)

# print list
print('Sorted :', myList)

Output:

Sorted list: [('t', 1), ('a', 2), ('g', 3), ('r', 4)]

5.Misusing The __init__ Method

The init is a reserved method in python classes that are used as constructors. It is invoked when Python allocates memory to a new class object or when an object is created from a class and it allows the class to initialize the attributes of the class. It is used to set the values of instance members for the class object. But programmers sometimes use it to return a value from the init method which is not the actual purpose of the init method. So, do take care of this.

6. Using assert statement as guarding condition

Assert provides an easy way to check any condition and fail execution if needed. So, developers use it frequently to check validity. But assert statements are recommended to be used only in tests. Let me explain to you why. When the python interpreter is invoked with the -o flag(optimize), the assert statements are deleted from the bytecode. So, if you have used assert statements in production code to validate something that block won’t be executed at all. This opens up a security threat. Hence, consider it using only in tests.

Incorrect:

assert re.match(VALID_EMAIL_REGEXP, email) is not None

Correct:

if not re.match(VALID_EMAIL_REGEXP, email):
     raise AssertionError

7.Unnecessary lambda expression

Functions in Python are the aggregation of related statements designed to perform a computational, logical task. Functions can be directly assigned to any variable, can be passed as an argument in another function, and so on. But this may not be intuitive for programmers coming from other programming languages.

Example:

def request(self, method, **kwargs):
    if method not in ("put", "post"):
        req.get_method = lambda: method.upper()

Better way:

def request(self, method, **kwargs):
    if method not in ("put", "post"):
        req.get_method = method.upper

End Notes

These are some common mistakes done by newcomers. Familiarize yourself more with the key nuances of Python, it will for sure help you optimize the use of the language while avoiding some of its more common errors.

I hope you find the pointers in this article helpful. Let’s connect on Linkedin. Thanks for reading if you reached here :).

Happy coding!

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

Gaurav Sharma 01 Jul 2021

Love Programming, Blog writing and Poetry

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Related Courses

image.name
0 Hrs 70 Lessons
5

Introduction to Python

Free