Unlock Powerful Python Tricks: Sets, Calendars, Enums, and More
This article showcases practical Python tricks—including set operations for deduplication, permission handling with set differences, calendar month calculations, enumerate with custom start indices, clean if‑else handling via enums, and iPython usage—providing concise code examples that boost everyday development productivity.
In this article we explore several handy Python tricks that are frequently used in daily development work.
Sets
Developers often forget that Python has a built‑in set type, preferring lists for everything. A set is an unordered collection of unique elements. Mastering sets can simplify many problems, such as extracting unique letters from a word:
myword = "NanananaBatman"
set(myword)
# Result: {'N', 'm', 'n', 'B', 'a', 't'}Another example shows how to remove duplicates from a list:
# first you can easily change set to list and other way around
mylist = ["a", "b", "c", "c"]
# let's make a set out of it
myset = set(mylist)
# myset will be: {'a', 'b', 'c'}
for element in myset:
print(element)
# and you can convert it back to a list
mynewlist = list(myset)
# mynewlist will be: ['a', 'b', 'c']Note that the order of elements may change when converting between list and set.
Permission Set Operations
Sets are useful for handling many‑to‑many relationships such as user permissions. The following demonstrates adding and removing permissions using set differences:
# this is the set of permissions before change
original_permission_set = {"is_admin", "can_post_entry", "can_edit_entry", "can_view_settings"}
# this is new set of permissions
new_permission_set = {"can_edit_settings", "is_member", "can_view_entry", "can_edit_entry"}
# permissions to add
new_permission_set.difference(original_permission_set)
# => {'can_edit_settings', 'can_view_entry', 'is_member'}
# permissions to remove
original_permission_set.difference(new_permission_set)
# => {'is_admin', 'can_view_settings', 'can_post_entry'}Using sets makes permission updates concise and error‑free.
Calendar Module
The calendar module helps determine the number of days in a month and the weekday of the first day. calendar.monthrange(year, month) returns a tuple (weekday, days) where weekday is 0‑6 (Mon‑Sun).
import calendar
calendar.monthrange(2020, 12) # (1, 31)
calendar.monthrange(2024, 2) # (3, 29) # leap yearYou can compute the weekday for any day by adding an offset:
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
offset = 3 # first weekday from monthrange for Feb 2024
for day in range(1, 30):
print(day, weekdays[(day + offset - 1) % 7])The datetime module provides a more direct way:
from datetime import datetime
mydate = datetime(2024, 2, 15)
datetime.weekday(mydate) # 3 (Thursday)
datetime.strftime(mydate, "%A") # 'Thursday'Enumerate with Start Index
The enumerate function accepts an optional start argument, allowing custom indexing:
mylist = ['a', 'b', 'd', 'c', 'g', 'e']
for i, item in enumerate(mylist, 16):
print(i, item)
# Output starts at 16: 16 a, 17 b, ...Clean If‑Else Handling with Enums
When many conditions are involved, using an Enum (or IntEnum) with a handler dictionary keeps the code tidy:
from enum import IntEnum
class StatusE(IntEnum):
OPEN = 1
IN_PROGRESS = 2
CLOSED = 3
def handle_open_status():
print('Handling open status')
def handle_in_progress_status():
print('Handling in‑progress status')
def handle_closed_status():
print('Handling closed status')
handlers = {
StatusE.OPEN.value: handle_open_status,
StatusE.IN_PROGRESS.value: handle_in_progress_status,
StatusE.CLOSED.value: handle_closed_status,
}
def handle_status_change(status):
if status not in handlers:
raise Exception(f'No handler found for status: {status}')
handlers[status]()Enum Module
The enum module provides Enum and IntEnum for managing constant groups. Example usage:
from enum import Enum, IntEnum
class MyEnum(Enum):
FIRST = "first"
SECOND = "second"
THIRD = "third"
class MyIntEnum(IntEnum):
ONE = 1
TWO = 2
THREE = 3
print(MyEnum.FIRST) # MyEnum.FIRST
print(MyEnum.FIRST.value) # 'first'
print(MyIntEnum.ONE == 1) # TrueEnums are especially helpful in medium‑sized codebases for managing constants and can be localized, e.g., with Django’s gettext_lazy.
iPython
iPython is an enhanced interactive Python shell. Install it with:
pip install ipythonAfter launching, you get a richer REPL with tab completion, system command shortcuts, and history navigation.
Reference: https://levelup.gitconnected.com/python-tricks-i-can-not-live-without-87ae6aff3af8 (article originally from CSDN).
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
