Check whether an integer is a power of two in Python

· 2 min

To check whether an integer is a power of two, I’ve deployed hacks like this:

def is_power_of_two(x: int) -> bool:
    return x > 0 and hex(x)[-1] in ("0", "2", "4", "8")

While this hex trick works, I’ve never liked explaining the pattern matching hack that’s going on here.

Today, I came across this tweet by Raymond Hettinger where he proposed an elegant solution to the problem. Here’s how it goes:

def is_power_of_two(x: int) -> bool:
    return x > 0 and x.bit_count() == 1

This is neat as there’s no hack and it uses a mathematical invariant to check whether an integer is a power of 2 or not. Also, it’s a tad bit faster.

Uniform error response in Django Rest Framework

· 3 min

Django Rest Framework exposes a neat hook to customize the response payload of your API when errors occur. I was going through Microsoft’s REST API guideline and wanted to make the error response of my APIs more uniform and somewhat similar to this example.

I’ll use a modified version of the quickstart example in the DRF docs to show how to achieve that. Also, we’ll need a POST API to demonstrate the changes better. Here’s the same example with the added POST API. Place this code in the project’s urls.py file.

Difference between constrained 'TypeVar' and 'Union' in Python

· 2 min

If you want to define a variable that can accept values of multiple possible types, using typing.Union is one way of doing that:

from typing import Union

U = Union[int, str]

However, there’s another way you can express a similar concept via constrained TypeVar. You’d do so as follows:

from typing import TypeVar

T = TypeVar("T", int, str)

So, what’s the difference between these two and when to use which? The primary difference is:

T’s type needs to be consistent across multiple uses within a given scope, while U’s doesn’t.

Don't wrap instance methods with 'functools.lru_cache' decorator in Python

· 6 min

Recently, fell into this trap as I wanted to speed up a slow instance method by caching it.

When you decorate an instance method with functools.lru_cache decorator, the instances of the class encapsulating that method never get garbage collected within the lifetime of the process holding them.

Let’s consider this example:

# src.py
import functools
import time
from typing import TypeVar

Number = TypeVar("Number", int, float, complex)


class SlowAdder:
    def __init__(self, delay: int = 1) -> None:
        self.delay = delay

    @functools.lru_cache
    def calculate(self, *args: Number) -> Number:
        time.sleep(self.delay)
        return sum(args)

    def __del__(self) -> None:
        print("Deleting instance ...")


# Create a SlowAdder instance.
slow_adder = SlowAdder(2)

# Measure performance.
start_time = time.perf_counter()
# ----------------------------------------------
result = slow_adder.calculate(1, 2)
# ----------------------------------------------
end_time = time.perf_counter()
print(f"Calculation took {end_time-start_time} seconds, result: {result}.")


start_time = time.perf_counter()
# ----------------------------------------------
result = slow_adder.calculate(1, 2)
# ----------------------------------------------
end_time = time.perf_counter()
print(f"Calculation took {end_time-start_time} seconds, result: {result}.")

Here, I’ve created a simple SlowAdder class that accepts a delay value; then it sleeps for delay seconds and calculates the sum of the inputs in the calculate method. To avoid this slow recalculation for the same arguments, the calculate method was wrapped in the lru_cache decorator. The __del__ method notifies us when the garbage collection has successfully cleaned up instances of the class.

Cropping texts in Python with 'textwrap.shorten'

· 3 min

Problem

A common interview question that I’ve seen goes as follows:

Write a function to crop a text corpus without breaking any word.

  • Take the length of the text up to which character you should trim.
  • Make sure that the cropped text doesn’t have any trailing space.
  • Try to maximize the number of words you can pack in your trimmed text.

Your function should look something like this:

def crop(text: str, limit: int) -> str:
    """Crops 'text' upto 'limit' characters."""

    # Crop the text.
    cropped_text = perform_crop()
    return cropped_text

For example, if text looks like this:

String interning in Python

· 5 min

I was reading the reference implementation of PEP-661: Sentinel Values and discovered an optimization technique known as String interning. Modern programming languages like Java, Python, PHP, Ruby, Julia, etc, performs string interning to make their string operations more performant.

String interning

String interning makes common string processing operations time and space-efficient by caching them. Instead of creating a new copy of string every time, this optimization method dictates to keep just one copy of string for every appropriate immutable distinct value and use the pointer reference wherever referred.

Structural subtyping in Python

· 8 min

I love using Go’s interface feature to declaratively define my public API structure. Consider this example:

package main

import (
    "fmt"
)

// Declare the interface.
type Geometry interface {
    area() float64
    perim() float64
}

// Struct that represents a rectangle.
type rect struct {
    width, height float64
}

// Method to calculate the area of a rectangle instance.
func (r *rect) area() float64 {
    return r.width * r.height
}

// Method to calculate the perimeter of a rectange instance.
func (r *rect) perim() float64 {
    return 2 * (r.width + r.height)
}

// Notice that we're calling the methods on the interface,
// not on the instance of the Rectangle struct directly.
func measure(g Geometry) {
    fmt.Println(g)
    fmt.Println(g.area())
    fmt.Println(g.perim())
}

func main() {
    r := &rect{width: 3, height: 4}

    measure(r)
}

You can play around with the example on Go Playground. Running it will print:

Automatic attribute delegation in Python composition

· 3 min

While trying to avoid inheritance in an API that I was working on, I came across this neat trick to perform attribute delegation on composed classes. Let’s say there’s a class called Engine and you want to put an engine instance in a Car. In this case, the car has a classic ‘has a’ (inheritance usually refers to ‘is a’ relationships) relationship with the engine. So, composition makes more sense than inheritance here. Consider this example:

Access 'classmethod's like 'property' methods in Python

· 2 min

I wanted to add a helper method to an Enum class. However, I didn’t want to make it a classmethod as property method made more sense in this particular case. Problem is, you aren’t supposed to initialize an enum class, and property methods can only be accessed from the instances of a class; not from the class itself.

While sifting through Django 3.2’s codebase, I found this neat trick to make a classmethod that acts like a property method and can be accessed directly from the class without initializing it.

Use __init_subclass__ hook to validate subclasses in Python

· 3 min

At my workplace, we have a fairly large Celery config file where you’re expected to subclass from a base class and extend that if there’s a new domain. However, the subclass expects the configuration in a specific schema. So, having a way to enforce that schema in the subclasses and raising appropriate runtime exceptions is nice.

Wrote a fancy Python 3.6+ __init_subclasshook__ to validate the subclasses as below. This is neater than writing a metaclass.