My Personal Top 5 Python Features That I Regret not Having Known Before (Vol. 1)

pwned
3 min readNov 4, 2024

--

Photo by Kevin Ku on Unsplash

It may sound trivial (and considering that I have been writing Python code for many years, it may be all the more embarrassing), but I have to admit that I never really had the first “trick” on my screen. We are talking about the so-called “The Walrus Operator”.

№1: The Walrus Operator (:=): Assign values within expressions for cleaner code:

Let’s say you have the following file, which should be read line by line:

# Hello.txt
Hello,
World
!

The most straight forward approaches would be something like the following, using a while- or a for-loop:

# First Approach
with open("Hello.txt", "r") as file_handler:
# iterate lines using while loop
line = file_handler.readline()
while line:
# Process the line here (e.g., print it)
print(line.strip()) # Strip removes the newline character

# Read the next line
line = file_handler.readline()

# Second Approach
with open('Hello.txt', 'r') as file:
for line in file:
# Process each line here
print(line.strip()) # Strip removes the newline character

Using the Walrus Operator, you can do the following:

# Walrus Approach using While-Loop
with open("Hello.txt", "r") as file_handler:
while line := file_handler.readline():
print(line.strip())

№2: Alphabets using the String-Module:

The string module is a treasure trove of tools for working with text in Python. One of its hidden gems is the ability to effortlessly generate various types of alphabets, saving you from writing tedious loops or manual character definitions.

import string

lowercase_alphabet = string.ascii_lowercase
uppercase_alphabet = string.ascii_uppercase
combined_alphabet = string.ascii_letters

print(lowercase_alphabet) # abcdefghijklmnopqrstuvwxyz
print(uppercase_alphabet) # ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(combined_alphabet) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

You can iterate through the alphabets to perform operations on each letter. enumerate() adds indices for convenient tracking:

# [...]

for index, letter in enumerate(string.ascii_uppercase):
print(f"Letter {index+1}: {letter}")

№3: Merging of dictionaries:

In Python 3.9 and above, merging dictionaries has become more straightforward and intuitive with the introduction of the | operator, known as the merge operator. This operator allows you to combine two dictionaries into a new one, retaining the entries from both dictionaries. If there are overlapping keys, the values from the right-hand dictionary will overwrite those from the left-hand dictionary. Here’s a simple example:

dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = dict1 | dict2

This provides a more readable solution for dictionary merging.

№4: Structural pattern matching:

Structural pattern matching was introduced in Python 3.10 and is a feature that allows developers to match complex data structures and decompose them into their constituent parts.

The core component of structural pattern matching is the match statement, which evaluates a value against a series of patterns and executes the corresponding block of code for the first match it finds. The syntax is straightforward:

def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"

№5: zoneinfo Module:

The zoneinfo module, introduced in Python 3.9, provides a way to work with time zones using the IANA time zone database, which offers a more comprehensive and up-to-date set of time zone information. This module allows to handle time zone conversions and manipulations in a more straightforward and efficient manner.

To utilize the zoneinfo module, you first need to import it and then create a ZoneInfo object representing a specific time zone. For example, to work with the "America/New_York" time zone, you would do the following:

from datetime import datetime
from zoneinfo import ZoneInfo

# Get the current time in UTC
utc_time = datetime.now(ZoneInfo("UTC"))
print("UTC Time:", utc_time)

# Convert UTC time to a specific time zone (e.g., New York)
ny_time = utc_time.astimezone(ZoneInfo("America/New_York"))
print("New York Time:", ny_time)

# Convert UTC time to another time zone (e.g., Tokyo)
tokyo_time = utc_time.astimezone(ZoneInfo("Asia/Tokyo"))
print("Tokyo Time:", tokyo_time)

Further Reading

Python 3.X Changelog: https://docs.python.org/3.{9, 10, 11, 12, 13, 14}/whatsnew/3.{9, 10, 11, 12, 13}.html

--

--

No responses yet