About Py Snack πΏ β Coding and Programming Telegram Channel
Bite-sized Python tips to write cleaner, smarter, and faster code. Learn best practices, refactoring techniques, and optimization strategies to improve your Python skills and code quality.
π¬ Feedback, questions, or collaboration? Reach out: @bashnxa
Follow @py_snack to stay updated with the latest learn and python trends and news
π‘ In Python 3.14, uuid6, uuid7, and uuid8 were added:
UUID v6 β monotonic, time-ordered replacement for v1 (better sorting, no MAC leaks).
UUID v7 β combines timestamp ordering with randomness β great for DB primary keys.
UUID v8 β custom format playground for app-specific needs.
π #python_3_14 #uuid #databases #performance #customization
65
1
0
Py Snack πΏ
Mar 29, 2026, 08:17 AM
π« Before:
data = b"abcdef" * 10**6
chunk = data[2:5] # makes a copy
β After:
# settings.py
data = b"abcdef" * 10**6
view = memoryview(data)[2:5] # zero-copy slice
π§ β€ memoryview avoids copying β slicing large bytes / bytearray objects creates views instead of duplicating data.
Perfect for parsing network packets, binary protocols, or huge files without ballooning memory usage.
π #memory #performance #python_internals #best_practices
58
0
0
Py Snack πΏ
Mar 29, 2026, 08:17 AM
π« Before:
from contextvars import ContextVar
A = ContextVar("A")
token = A.set("val")
try:
...
finally:
A.reset(token)
β After (3.14+):
from contextvars import ContextVar
A = ContextVar("A")
with A.set("val"):
...
π§ β€ Token is now a context manager.
π #python_3_14 #contextvars #clean_code #syntax_sugar
66
0
0
Py Snack πΏ
Mar 29, 2026, 08:17 AM
π« Before:
from uuid import uuid4
key = uuid4() # unique, but unordered
β After (3.14+):
from uuid import uuid7
key = uuid7() # unique + chronologically sortable
π§ β€ UUID v7 combines randomness with time ordering β perfect for DB keys (uniqueness + natural sort).
π #python_3_14 #uuid #databases #performance
63
0
0
Py Snack πΏ
Mar 29, 2026, 08:17 AM
π« Before:
if user.is_admin:
delete_all_data()
else:
raise PermissionError("Not allowed!")
β After (Python 3.11+):
user.is_admin or raise PermissionError("Not allowed!")
delete_all_data()
π§ β€ raise as an expression makes the code shorter and cleaner.
π #basics #clean_code #syntax_sugar #python_3_11 #exceptions #tips #best_practices #control_flow
106
0
0
Py Snack πΏ
Mar 29, 2026, 08:17 AM
π« Before:
def get_config_value(key: str) -> str:
with open("config.json") as f:
config = json.load(f)
return config[key]
β After:
from functools import cache
@cache
def get_config_value(key: str) -> str:
with open("config.json") as f:
config = json.load(f)
return config[key]
π§ β€ https://t.me/cache prevents repeated file reads (static configs only - use https://t.me/lru_cache(1) + os.path.getmtime() for dynamic)
π #basics #functions #performance #cache #functools #pythonic #clean_code #tips #optimization
92
0
Py Snack πΏ
Mar 29, 2026, 08:17 AM
π« Before:
class Singleton:
_instance: "Singleton" | None = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
β After:
# settings.py
class Settings:
...
settings = Settings()
π§ β€ Python modules are already singletons by nature β no need for custom Singleton classes that introduce hidden state, inheritance issues, and confusing behavior.
π #basics #pitfalls #singleton #clean_code #pythonic
73
0
0
Py Snack πΏ
Mar 29, 2026, 08:17 AM
π« Before:
for item in data:
try:
self.assertEqual(process(item), expected(item))
except AssertionError as e:
print(f"Failed for {item}: {e}")
β After (Python 3.13+):
from test.support import subTests
with subTests(self):
for item in data:
with self.subTest(item=item):
self.assertEqual(process(item), expected(item))
π§ β€ subTests from http://test.support/ simplifies running multiple assertions inside one test.
β€ Failures in one subtest donβt stop others β better granularity and clearer reports.
β€ Perfect for parameterized or bulk input testing.
π #basics #testing #unittest #pythonic #3_13_update #subTests #clean_code #tips #test_automation
133
0
0
Py Snack πΏ
Mar 29, 2026, 08:17 AM
π« Before:
def calculate_discount(price: float, discount: float) -> float:
"""Calculate final price after discount."""
if price < 0:
raise ValueError("Price cannot be negative")
if not 0 <= discount <= 100:
raise ValueError("Discount must be between 0 and 100")
return price * (1 - discount / 100)
β After:
from pydantic import validate_call
from typing import Annotated
from pydantic.types import Gt, Ge, Le
@validate_call
def calculate_discount(
price: Annotated[float, Gt(0)],
discount: Annotated[float, Ge(0), Le(100)]
) -> float:
return price * (1 - discount / 100)
π§ β€ typing. Annotated with predicates like Gt/Le (from pydantic or typing_extensions) embeds constraints directly in type hints, keeping signatures self-documenting while staying type-checker friendly.
π #basics #pydantic #typing #annotations #validation #pythonic #clean_code #tips #type_safety #best_practices
131
0
Py Snack πΏ
Mar 29, 2026, 08:17 AM
π« Before:
def clean(data: list[int]) -> list[int]:
for x in data:
if x < 0:
data.remove(x)
return data
print(clean([1, -2, -3, 4])) # [1, -3, 4]
β After:
def clean(data: list[int]) -> list[int]:
return [x for x in data if x >= 0]
print(clean([1, -2, -3, 4])) # [1, 4]
π§ β€ Removing while iterating shifts indexes and skips items.
π #basics #lists #pythonic #clean_code #pitfalls #tips #list_comprehension #best_practices #performance
104
0
0
Py Snack πΏ
Mar 17, 2026, 11:57 PM
π« Before:
if user.is_authenticated:
send_welcome_email(user)
β After
user.is_authenticated and send_welcome_email(user)
π§ β€ In Python, and evaluates the second expression only if the first is true, enabling concise conditional calls without else.
π #basics #clean_code #short_circuit #tips #syntax_sugar #best_practices
113
0
0
Py Snack πΏ
Dec 6, 2025, 02:42 AM
π« Before:
def move_file(src, dst, overwrite=False): ...move_file("a.txt", "b.txt", True)
β After
def move_file(src, dst, /, *, overwrite=False): ...move_file("a.txt", "b.txt", overwrite=True)
π§ β€ / makes src and dst positional-only β prevents accidental argument mix-ups.
β€ * makes overwrite keyword-only β avoids confusing third positional arg.
π ?q=%23basics ?q=%23functions ?q=%23clean_code
117
0
0
Py Snack πΏ
Dec 6, 2025, 02:42 AM
π« Before:
if type(obj) == list: handle_list(obj)
β After
if isinstance(obj, list): handle_list(obj)
π§ β€ type(obj) == list checks for exact type only β wonβt catch subclasses!
β€ isinstance considers inheritance β more correct and flexible.
β€ Use isinstance for type checks by default.
π ?q=%23basics ?q=%23pitfalls ?q=%23type_checking ?q=%23isinstance ?q=%23clean_code ?q=%23oop ?q=%23tips
122
0
0
Py Snack πΏ
Dec 3, 2025, 07:34 AM
π« Before:
import asyncio, aiohttpTOTAL_REQUESTS = 1_000_000async def fetch(session, url): async with session.get(url) as resp: return await resp.text()async def main(): urls = [f"https://api.site/{i}" for i in range(TOTAL_REQUESTS)] async with aiohttp. ClientSession() as session: tasks = [fetch(session, url) for url in urls] await asyncio.gather(*tasks) # π₯ OOM / rate-limitasyncio.run(main())
β After
import asyncio, aiohttpTOTAL_REQUESTS = 1_000_000sem = asyncio. Semaphore(1000)async def fetch(session, url): async with sem: try: async with session.get(url) as resp: return await resp.text() except aiohttp. ClientError: return Noneasync def main(): urls = [f"https://api.site/{i}" for i in range(TOTAL_REQUESTS)] async with aiohttp. ClientSession() as session: for i in range(0, len(urls), 10_000): chunk = urls[i:i+10_000] tasks = [fetch(session, url) for url in chunk] await asyncio.gather(*tasks)asyncio.run(main())
π§ β€ Avoid memory blowups & rate-limit bans. Use semaphores + chunking like a pro.
π ?q=%23asyncio ?q=%23aiohttp ?q=%23performance
93
0
Showing 14 of 14 posts
No more posts
0
0
0
No reviews yet. Be the first to share your experience!