Code With Python
39K subscribers
843 photos
24 videos
22 files
747 links
This channel delivers clear, practical content for developers, covering Python, Django, Data Structures, Algorithms, and DSA – perfect for learning, coding, and mastering key programming skills.
Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
a = 100
b = 100
print(f"a == b: {a == b}") # Output: a == b: True
print(f"a is b: {a is b}") # Output: a is b: True (for integers -5 to 256)

c = 300
d = 300
print(f"c == d: {c == d}") # Output: c == d: True
print(f"c is d: {c is d}") # Output: c is d: False (for integers outside -5 to 256)

s1 = "hello"
s2 = "hello"
print(f"s1 is s2: {s1 is s2}") # Output: s1 is s2: True (string interning for short, simple strings)

s3 = "hello world!"
s4 = "hello world!"
print(f"s3 is s4: {s3 is s4}") # Output: s3 is s4: False (interring not guaranteed for complex strings)

CPython pre-allocates and caches integer objects in the range of -5 to 256. Similarly, short, simple string literals are often "interned" for performance. This means that multiple references to these specific values will point to the same object in memory, making is return True. This is an implementation detail and should not be relied upon for general equality checks, where == is the correct semantic choice.

Mutable Default Arguments

A common pitfall for new and experienced developers alike arises from mutable objects used as default arguments in function definitions. Default arguments are evaluated once when the function is defined, not on each call.

def add_item_to_list(item, data=[]):
data.append(item)
return data

list1 = add_item_to_list(1)
print(f"List 1: {list1}") # Output: List 1: [1]

list2 = add_item_to_list(2)
print(f"List 2: {list2}") # Output: List 2: [1, 2] - Unobvious! `data` is the same list object as before.

list3 = add_item_to_list(3, []) # Passed a new list
print(f"List 3: {list3}") # Output: List 3: [3]
print(f"List 2 after List 3: {list2}") # Output: List 2 after List 3: [1, 2] - Unchanged.

The "unobvious" part is that data in the list2 call is the same list object that was modified by list1. The standard workaround is to use None as a sentinel value:

def add_item_to_list_safe(item, data=None):
if data is None:
data = []
data.append(item)
return data

list4 = add_item_to_list_safe(1)
print(f"List 4 (safe): {list4}") # Output: List 4 (safe): [1]

list5 = add_item_to_list_safe(2)
print(f"List 5 (safe): {list5}") # Output: List 5 (safe): [2] - Now as expected.


Chained Comparisons

Python allows for elegant chained comparisons, which can sometimes surprise those accustomed to other languages that require explicit logical operators (and, &&).

x = 7

# Traditional (and verbose)
if 0 < x and x < 10:
print("x is between 0 and 10 (exclusive) - traditional")

# Python's elegant chained comparison
if 0 < x < 10:
print("x is between 0 and 10 (exclusive) - chained")

# More complex chaining
a, b, c = 1, 2, 3
if a < b == c:
print("a is less than b, and b is equal to c") # False, since b != c

This unobvious syntactic sugar evaluates from left to right, short-circuiting if any comparison is false. It is equivalent to (0 < x) and (x < 10) but offers a cleaner, more mathematical notation.

The Walrus Operator (:=)

Introduced in Python 3.8, the assignment expression operator :=, informally known as the "walrus operator," allows you to assign a value to a variable as part of an expression. This can lead to more concise code in situations where you would otherwise repeat an expression or assign it on a separate line.
1
# Without walrus
data = [1, 2, 3]
n = len(data)
if n > 0:
print(f"List has {n} items")

# With walrus
if (n := len(data)) > 0:
print(f"List has {n} items")

# In a loop condition
records = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
processed_records = []
while (record := records.pop()) if records else None: # Unobvious but powerful loop condition
processed_records.append(record)
print(f"Processing: {record}")
print(f"Processed all: {processed_records}")

The := operator enables patterns that are less common in earlier Python versions, making code more dense and, at times, more efficient by avoiding redundant computations, but it requires a slightly different way of thinking about expressions.

Conclusion

Python's journey from a simple scripting language to a powerhouse for diverse applications has imbued it with a rich set of features. Exploring these unobvious behaviors, from the mathematical elegance of ~ and the logical quirks of all() with empty sequences to the subtle optimizations of object caching and the syntactic conciseness of chained comparisons and the walrus operator, strengthens a developer's grasp of the language's core. These nuances are not merely trivia; they are cornerstones for writing robust, efficient, and truly Pythonic code.

---
tags: python, programming, unobvious, nuances, features, operators, all, any, bitwise, walrus, is, equals, mutable defaults

━━━━━━━━━━━━━━━
By: @DataScience4
4
The Python Standard REPL: Try Out Code and Ideas Quickly

📖 The Python REPL gives you instant feedback as you code. Learn to use this powerful tool to type, run, debug, edit, and explore Python interactively.

🏷️ #intermediate #tools
3
🏆 Connecting Python to MySQL: `mysql-connector`

📢 Master connecting Python to MySQL with `mysql-connector-python`, and troubleshoot 'module not found' errors for seamless data integration.

Tap to unlock the complete answer and gain instant insight.

━━━━━━━━━━━━━━━
By: @DataScience4
2👍1
🏆 Generate Website Screenshots with Python Flask

📢 Generate website screenshots effortlessly! Learn to build your own tool using Python and Flask. Essential for web development and QA.

Tap to unlock the complete answer and gain instant insight.

━━━━━━━━━━━━━━━
By: @DataScience4
How to Convert Bytes to Strings in Python

📖 Turn Python bytes to strings, pick the right encoding, and validate results with clear error handling strategies.

🏷️ #basics
1
Tip for clean tests in Python:

In most cases, your tests should cover:

- all happy path scenarios
- edge/corner/boundary cases
- negative tests
- security checks and invalid inputs

import uuid
from dataclasses import dataclass
from typing import Optional


@dataclass
class User:
    username: str


class InMemoryUserRepository:
    def __init__(self):
        self._users = []

    def add(self, user: User) -> None:
        self._users.append(user)

    def search(self, query: Optional[str] = None) -> list[User]:
        if query is None:
            return self._users
        else:
            return [
                user
                for user in self._users
                if query in user.username
            ]


# happy path
def test_search_users_without_query_lists_all_users():
    user1 = User(username="john@doe.com")
    user2 = User(username="marry@doe.com")
    repository = InMemoryUserRepository()
    repository.add(user1)
    repository.add(user2)

    assert repository.search() == [user1, user2]


# happy path
def test_search_users_with_email_part_lists_all_matching_users():
    user1 = User(username="john@doe.com")
    user2 = User(username="bob@example.com")
    user3 = User(username="marry@doe.com")
    repository = InMemoryUserRepository()
    repository.add(user1)
    repository.add(user2)
    repository.add(user3)

    assert repository.search("doe") == [user1, user3]


# edge test case
def test_search_users_with_empty_query_lists_all_users():
    user1 = User(username="john@doe.com")
    user2 = User(username="marry@doe.com")
    repository = InMemoryUserRepository()
    repository.add(user1)
    repository.add(user2)

    assert repository.search("") == [user1, user2]


# negative test case
def test_search_users_with_random_query_lists_zero_users():
    user1 = User(username="john@doe.com")
    repository = InMemoryUserRepository()
    repository.add(user1)

    assert repository.search(str(uuid.uuid4())) == []


# security test
def test_search_users_with_sql_injection_has_no_effect():
    user1 = User(username="john@doe.com")
    repository = InMemoryUserRepository()
    repository.add(user1)

    repository.search("DELETE FROM USERS;")
    assert repository.search() == [user1]


👉 @DataScience4
Please open Telegram to view this post
VIEW IN TELEGRAM
5👍3
Quiz: How to Serve a Website With FastAPI Using HTML and Jinja2

📖 Review how to build dynamic websites with FastAPI and Jinja2, and serve HTML, CSS, and JS with HTMLResponse and StaticFiles.

🏷️ #intermediate #api #front-end #web-dev
How to Use Google's Gemini CLI for AI Code Assistance

📖 Learn how to use Gemini CLI to bring Google's AI-powered coding assistance directly into your terminal to help you analyze and fix code.

🏷️ #intermediate #ai #tools
evaluation | AI Coding Glossary

📖 The process of measuring how well an AI system or model meets its objectives.

🏷️ #Python
1
vector | AI Coding Glossary

📖 An ordered array of numbers that represents a point, magnitude, and direction.

🏷️ #Python
Topic: Python Standard Library

📖 Practical Python standard library tutorials to master datetime, pathlib, argparse, subprocess, logging, and more. Write faster, cleaner, dependency-free code.

🏷️ #86_resources
1
Topic: Algorithms Tutorials

📖 Learn Python algorithms: sorting, searching, graphs, DP, Big O. Use heapq, bisect, deque, lru_cache, timeit. Study practical tips and FAQs for interviews.

🏷️ #22_resources
1
Meet Our Team

📖 Meet Real Python's team of expert Python developers, educators, and 190+ contributors bringing real-world experience to create practical Python education.

🏷️ #Python
🔥1
Pydantic AI | AI Coding Tools

📖 A Python framework for building typed LLM agents leveraging Pydantic.

🏷️ #Python
bias | AI Coding Glossary

📖 A systematic deviation from truth or fairness.

🏷️ #Python
1
Google Antigravity | AI Coding Tools

📖 An agent-first IDE where AI agents operate the editor, terminal, and browser and produce verifiable Artifacts of their work.

🏷️ #Python
nearest neighbor | AI Coding Glossary

📖 The data point in a reference set that has the smallest distance to a query point.

🏷️ #Python
autoregressive generation | AI Coding Glossary

📖 A method in which a model produces a sequence one token at a time, with each token conditioned on all previously generated tokens.

🏷️ #Python
Quiz: Build a Python MCP Client to Test Servers From Your Terminal

📖 Learn how to create a Python MCP client, start an AI-powered chat session, and run it from the command line. Check your understanding.

🏷️ #intermediate #ai #projects
3