Learn Python Coding
40.2K subscribers
701 photos
36 videos
24 files
497 links
Learn Python through simple, practical examples and real coding ideas. Clear explanations, useful snippets, and hands-on learning for anyone starting or improving their programming skills.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Python can substitute an empty context manager without conditions inside!

It often happens that a resource needs to be opened via with, and sometimes the object is already ready and there's no need to open anything.

This usually leads to code duplication or conditions around with:

if need_open:
f = open(...)
else:
f = existing_file

`nullcontext(obj) behaves like an empty context manager and allows you to maintain a single execution flow.

This is especially useful for APIs, tests, optional resources, dependency injection, and functions that can accept both a path and a ready-made object.

with ctx as resource:
process(resource)

But note that nullcontext() does not close the passed object — it simply passes it on further.

🔥 nullcontext() helps to unify scenarios with optional context managers and significantly simplifies the architecture of IO code.

#Python #ContextManager #CodingTips #DevLife #Programming #Tech

Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A

🚀 Level up your AI & Data Science skills with HelloEncyclo — a growing all-in-one platform featuring hands-on courses in LLMs, Deep Learning, MLOps, Data Engineering, and more.
13 courses live + 40+ coming soon
🎯 One access, lifetime updates
🔑 Use code: PRESALE-BOOK-WAVE-2GFG
👉 https://helloencyclo.com/?ref=HUSSEINSHEIKHO
1
Do you know that Python allows you to get all the object's attributes with one function without additional code? 🐍

When you need to quickly check the state of an object, many manually access the attributes or dig into __dict__.

But for this, Python already has a built-in function vars().

vars(obj)

It returns a dictionary of all the object's attributes, including the current state of the instance.

{'x': 10}

This is useful for debugging, logging, serialization, ORM, and analyzing the runtime state of objects.

print(vars(user))

Also, vars() works with modules, classes, and any objects with dict.

vars(module)

🔥
vars()` — a rather underrated tool for quickly analyzing the state of objects during execution.

#Python #Coding #Programming #Debugging #TechTips #DevLife

Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
2
Unpacking the remaining elements 🧩

Sometimes you need to extract the first and last elements from a list, while grouping everything in the middle separately. Instead of struggling with slicing ([1:-1]), use the asterisk (*). ⭐️

data = ["CEO", "Middle Python Dev", "Junior Dev", "QA", "HR"]

# The asterisk automatically collects everything "extra" into a separate list.
boss, *team, hr = data

print(boss) # CEO
print(team) # ['Middle Python Dev', 'Junior Dev', 'QA']
print(hr) # HR

#Python #Coding #DataScience #DevLife #Programming #Tech

Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
2🔥1
Creating Nested Dictionary Values using `setdefault()` 🔥

When grouping data, it's often necessary to check if a key exists, create a container for it, and then add a value.

For example, distributing users by role. Without special methods, this usually involves a separate key check.

users = [
("admin", "alex"),
("user", "max"),
("admin", "kate"),
]

groups = {}

for role, name in users:
if role not in groups:
groups[role] = []

groups[role].append(name)


The setdefault() method allows you to perform this operation directly when accessing the dictionary. If the key exists, it returns its current value. If the key is missing, the provided value is written to the dictionary and then returned:

groups = {}

for role, name in users:
groups.setdefault(
role,
[],
).append(name)


The result is the same structure without a separate key existence check:

print(groups)

# {
# 'admin': ['alex', 'kate'],
# 'user': ['max']
# }


It's important to note that the expression of the second argument is evaluated every time setdefault() is called, even if the key already exists. Therefore, you should avoid creating expensive objects or performing functions with side effects there:

value = cache.setdefault(
key,
build_value(),
)


In this code, build_value() will be called before the method itself is executed. If the value creation should only happen when the key is missing, it's better to use an explicit check or a suitable data structure, such as defaultdict.

🔥 setdefault() is well-suited for compactly initializing simple mutable containers when grouping and aggregating data. However, it's important to remember that the provided value is evaluated regardless of whether the key exists.

#Python #Coding #Dicts #Programming #CodeTips #DevLife

Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
Please open Telegram to view this post
VIEW IN TELEGRAM
2