Python Learning
5.76K subscribers
568 photos
2 videos
106 files
129 links
Python learning resources

Beginner to advanced Python guides, cheatsheets, books and projects.

For data science, backend and automation.
Join πŸ‘‰ https://rebrand.ly/bigdatachannels

DMCA: @disclosure_bds
Contact: @mldatascientist
Download Telegram
🐍 Python’s Secret Memory Saver: __slots__ ⚑️

πŸ‘‰ Most Python tutorials teach you Object-Oriented Programming (OOP) using self.variable = value. But almost none mention what happens under the hood or how it can quietly eat up your RAM.

When you create thousands or millions of object instances, Python’s default behavior wastes a massive amount of memory. Here is how __slots__ fixes that.

β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

πŸ”Ή 1. The Hidden Problem with Default Python Classes

By default, Python stores an object's attributes in a dynamic dictionary called __dict__.

πŸ‘‰ Why this is a problem:

❌ Dictionaries are flexible, but extremely memory-heavy.
❌ Every single instance gets its own dictionary overhead.
❌ If you instantiate 100,000 objects, your application’s RAM usage skyrockets.

β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

πŸ”₯ 2. The Solution: __slots__

__slots__ tells Python:
Do not create a dynamic
__dict__ for this class. Only allow these specific attribute names.



β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

πŸ”Ή 3. Standard Class vs. Slotted Class

❌ Standard Class (Uses Heavy __dict__):

class DataPoint:

def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z


βœ… Optimized Class with __slots__:

class DataPoint:
# Restrict attributes & eliminate __dict__
__slots__ = ("x", "y", "z")

def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z


β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

πŸ“Š 4. The Real-World Impact

By adding that single line of code (__slots__):

βœ”οΈ ~60% to 70% reduction in memory usage across large object lists.
βœ”οΈ Faster attribute access (up to 20% faster speed because Python skips dictionary lookups).

β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

⚠️ 5. The Trade-Off (What You Must Know)

Because __slots__ locks down your object structure:

❌ You cannot dynamically add new attributes at runtime (e.g., point.new_var = 10 will throw an AttributeError).

β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

❔ 6. When Should You Use It?

βœ”οΈ Working with huge datasets or simulation objects in memory.
βœ”οΈ Building high-performance backend microservices.
βœ”οΈ Designing lightweight data structures (like custom Nodes, Vectors, or Points).
❀3
Forwarded from Programming Quiz Channel
Topic: Python

πŸ” Quick look before the question:

def outer():
x = 10
def inner():
nonlocal x
x += 5
return x
return inner

f = outer()
print(f())
print(f())
4 Different Patterns in Python
❀4
Python for Data Science Cheat Sheet.pdf
372.3 KB
Python for Data Science Cheatsheet
πŸ‘1πŸ”₯1
🐍 Python’s Hidden Loop Feature: for...else

πŸ‘‰ Did you know else isn't just for if statements?

Python has a unique feature almost never mentioned in beginner tutorials: you can attach an else block directly to a for or while loop.

πŸ”Ή How It Works

The else block executes ONLY if the loop finishes completely without hitting a break statement.

πŸ”Ή The Difference

❌ Traditional Way (Requires a messy flag variable):

found = False
for user in users:
if user == "Alex":
found = True
break

if not found:
print("User not found!")


βœ… Pythonic Way (Using for...else):

for user in users:
if user == "Alex":
print("User found!")
break
else:
print("User not found!")



πŸ”Ή Why Use It?

βœ”οΈ Eliminates unnecessary boolean flags (like found = True).
βœ”οΈ Cleaner, more readable syntax for search functions.
❀2πŸ‘1
python-cheat-sheet.pdf
155.6 KB
Python CheatSheet
❀2πŸ”₯1
⚑️ Python’s 1-Line Speed Booster: @lru_cache

πŸ‘‰ Did you know you can make slow Python functions run up to 100x faster by adding a single line of code?

Most tutorials skip functools.lru_cache, but it’s one of Python’s best built-in performance hacks.

πŸ”Ή How It Works

It automatically caches (remembers) the results of function calls. If you call the function with the same inputs again, Python skips the heavy computation and returns the saved answer instantly.

πŸ”Ή Code Comparison

❌ Slow (Re-calculates every single call):

def get_user_data(user_id):
# Imagine an expensive database query here
return fetch_from_db(user_id)


βœ… Very Fast (Remembers previous results):

from functools import lru_cache


@lru_cache(maxsize=128)
def get_user_data(user_id):
# Only runs ONCE per unique user_id
return fetch_from_db(user_id)



πŸ”Ή Use It to:

βœ”οΈ Speedup repetitive API calls, math calculations, or DB queries.
βœ”οΈ No third-party libraries needed (built into Python's standard library).
βœ”οΈ Prevent unnecessary server load.
❀1πŸ‘1