The Talent500 Blog
4 effective tips and tricks to write better Python code 1

4 effective tips and tricks to write better Python code

Python is one of the most discussed programming languages among tech professionals at present. Not only for software development but also for machine learning and data science, Python is the preferred choice. Due to its fairly easy learning curve and mature and supportive community, new learners can get started easily. Also, hundreds of open-source libraries and frameworks, and the versatility and efficiency of Python make it a valuable programming language to add to your skills.

This article shares some tips and tricks for beginners and experienced programmers to write better Python code. The tips will help write more readable and faster code quickly.

1. Start using list comprehension instead of for loops 

For loops in Python code can cause unnecessary nesting that results in hard-to-read and maintain code. You can make your Python code much simpler with a list comprehension. It is a more straightforward and elegant way to create lists from existing lists. Using brackets, you can repeatedly execute each iteration with a single line of code. You can make your code time and space efficient by replacing loops and iterative statements with a list comprehension.

Here’s the usual syntax for list comprehension:

newList = [ expression(element) for element in oldList if condition ]

In practical applications, it is used like this:

# Loop iteration using list comprehension

List = [character for character in ‘HackerNoon’]

 # Displaying list

print(List)

# Output

# [‘H’, ‘a’, ‘c’, ‘k’, ‘e’, ‘r’, ‘N’, ‘o’, ‘o’, ‘n’]”

2. Using NotImplementedError for offensive programming

Python comes with an in-built NotImplementedError exception, a valuable feature for offensive programming. In offensive programming, developers avoid defensive principles when dealing with software bugs.

One example is when we control the input to align it with the format accepted by our code. It is not easy to sanitize every input, and it can be an inconvenience for future development.

Have a look at the code below in which we define a registering decorator and some functions:

import math

REGISTRY = {}

def register(name):

   def _decorator(fn):

     REGISTRY[name] = fn

     return fn

   return _decorator

@register(“relu”)

def rectified(x):

   return x if x > 0 else 0

@register(“sigmoid”)

def sigmoid(x):

   return 1/(1 + math.exp(-x))

def activate(x, funcname):

   if funcname not in REGISTRY:

     raise NotImplementedError(f”Function {funcname} is not implemented”)

   else:

     func = REGISTRY[funcname]

     return func(x)

print(activate(1.23, “relu”))

print(activate(1.23, “sigmoid”))

print(activate(1.23, “tanh”))

Here we used the NotImplementedError with a custom error message for the function activate(). The output of the code will be:

1.23

0.7738185742694538

Traceback (most recent call last):

  File “/Users/MLM/offensive.py”, line 28, in <module>  

print(activate(1.23, “tanh”))

  File “/Users/MLM/offensive.py”, line 21, in activate

   raise NotImplementedError(f”Function {funcname} is not implemented”)

NotImplementedError: Function tanh is not implemented

The result of the first two functions is printed, but the third function fails as we haven’t defined the tanh function yet.

This is an example of how you can use the NotImplementedError: in places in your code that still don’t meet the validity of the conditions but later on will have validation as the project proceeds.

3. Use generators to save memory 

In Python, the basic function of a generator is to evaluate the elements of a code on demand. As the syntax for list comprehension, here you use parentheses instead of square brackets. 

Here’s a code to generate the square of all even numbers in a list using generators: 

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(“The given list is:”, myList)

mygen = (element ** 2 for element in myList if element % 2 == 0)

print(“Elements obtained from the generator are:”)

for ele in mygen:

   print(ele)

The output:

The given list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Elements obtained from the generator are:

4

16

36

64

100

Beginners might find it hard to decide how the list comprehension differs from generators, given that their syntax is almost identical. 

Unlike list or set comprehension, generator comprehension does not initialize any objects. This is how using a generator comprehension lowers the memory requirement for a program. 

4. Define default values in Dictionaries with .get() and .setdefault()

Beginners often struggle with providing a default value for the Dictionaries function in their Python code. You can forget about assignment default value with the use of .setdefault() and .get().

With the .setdefault() method, you can set dict[key]=default if there is no key for the dict function already. You set the .setdefault() like this:

dict.setdefault(key, default=None)

Example code:

a_dictionary = {“a”: 1, “b”: 2, “d”: 4}

a_dictionary.setdefault(“c”, 3)

print(a_dictionary)

The output of the above code would look like this:

{‘a’: 1, ‘b’: 2, ‘d’: 4, ‘c’: 3}

The same functionality can be achieved using the .get() method, but you pass a default value for the key here. Here’s how it works:

a_dictionary = {“a”: 1, “b”: 2, “d”: 4}

print(a_dictionary.get(“c”, 3))

print(a_dictionary)

The output of the above code:

3

{‘a’: 1, ‘b’: 2, ‘d’: 4}

Conclusion 

Python has scope in multiple fields, and as you learn the scope of the language, you will know more tricks to optimize your code.

Talent500 is looking for python developers who want to join dynamic engineering teams at some of the biggest global companies. Sign up here to know more.

 

0
Satya Prakash Sharma

Satya Prakash Sharma

DevOps engineer at Talent500. Helping maintain security and infrastructure. Loves to develop applications. Lives for adventure!

Add comment