5 Advanced Code snippets for your Python programs

5 Advanced Code snippets for your Python programs

Use them and let people wonder

Photo by Joe Yates on Unsplash

Today I’ll share a few snippets with you from the book Python Tricks: The Book. This book has a lot of in-depth information about a few snippets we use daily and help you understand how they work.

I’d recommend you have a look for yourself after reading this article.

1. Use __repr__ & __str__ methods for better representation of a class object

class Glass:
    def __init__(self, reflct):
    self.reflct = reflct
glass = Glass('MIRROR')
glass
#OUTPUT
<__main__.Glass object at 0x0000028D48967550>
print(glass)
#OUTPUT
<__main__.Glass object at 0x0000028D48967550>
The string representation of the object is not been overridden which is why you are seeing this.
class Glass:
    def __init__(self, reflct):
        self.reflct = reflct
    def __str__(self):
        print('inside __str__ method')
    def __repr__(self):
        print('inside __repr__ method')
# This will all statements will use class __str__ method
>>> '{}'.format(glass)
>>> str(glass)
>>> print(glass)
#OUTPUT
inside __str__ method
# This will use __repr__ method
>>> glass
#OUTPUT
inside __repr__ method

2. Cloning objects in Python

In Python assign statements do not create copies of objects they only bind names to an object.

Shallow copy

It creates a new collection object and then populates it with references to the child objects found in the original. Thus, won’t create copies of the child objects themselves.

a = [[1, 2, 3], [4, 3, 5]]
b = list(a) # makes a shallow copy
a[0][0] = 'x'

#OUTPUT
Before
[[1, 2, 3], [4, 3, 5]]
[[1, 2, 3], [4, 3, 5]]
After
[['x', 2, 3], [4, 3, 5]]
[['x', 2, 3], [4, 3, 5]]

Deep copy

It creates a new collection object and then recursively populates it with copies of the child objects found in the original. This way it creates a fully independent clone of the original object and all of its children.

import copy

a = [[1, 2, 3], [4, 3, 5]]
b = copy.deepcopy(a)

a[0][0] = 'x'

#OUTPUT
Before
[[1, 2, 3], [4, 3, 5]]
[[1, 2, 3], [4, 3, 5]]
After
[['x', 2, 3], [4, 3, 5]]
[[1, 2, 3], [4, 3, 5]]

3. Inline list comprehension

The best way to populate a list in the Pythonic way is to just add the expression along with the loop.

This one-liner is hard to digest at first if you are a C or C++ developer but in Python, one-liners are just much more readable once you get used to the language.

values = [expression for item in collection]

3. Get N-th largest or N-th smallest elements in a list

This snippet may not be useful in daily scenarios but sometimes you might need N-th largest/smallest elements of a list and you might think you have to write the logic from scratch but fear not the in-built module comes to the rescue.

import heapq

scores = [1, 10, 11, 2, 5, 6]

print(heapq.nlargest(3, scores)) # [11, 10, 6]
print(heapq.nsmallest(5, scores)) # [1, 2, 5, 6, 10]

4. Using Decorators like a Pro!

Now before diving into the concept of decorators, would be an excellent moment to refresh your memory on the properties of first-class functions in Python.

What You Can Do With Python Functions
*Python functions are crazy!*
python.plainenglish.io

Decorators are complicated at first but highly useful features that you’ll often encounter in third-party frameworks and the Python standard library.

Decorators allow you to define reusable building blocks that can change or extend the behavior of other functions.

def uppercase(func):
    def wrapper():
        originalResult = func()
        modifiedResult = originalResult.upper()
        return modifiedResult
    return wrapper

@uppercase
def greet():
    return 'Hello World!'
print(greet())

# OUTPUT
HELLO WORLD!

5. Chain mapping: searching multiple dictionaries as a single mapping

The collections.ChainMap data structure groups multiple dictionaries into a single mapping.

Lookups search the underlying mappings one by one until a key is found.

Insertions, updates, and deletions only affect the first mapping added to the chain.

from collections import ChainMap

d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
chain = ChainMap(d1, d2)

# ChainMap searches each collection in the chain
# from left to right until it finds the key (or fails):
print(chain)

# OUTPUT
# ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4})

Did you find this article valuable?

Support Rahul's Tech Blog by becoming a sponsor. Any amount is appreciated!