🐍 An Interesting (and Sneaky) Python Bug I Ran Into I’ve been working through Fluent Python recently, and one part, "Mutable Types as Parameter Defaults: Bad Idea", reminded me of a classic pitfall that even experienced developers stumble into: using mutable objects as default parameters. It looks innocent enough: def add_item(item, container=[]): container.append(item) return container But here’s the twist: Python evaluates default parameter values only once—when the function is defined, not each time it’s called. So instead of getting a fresh list every call, you get shared state: add_item(1) # [1] add_item(2) # [1, 2] # surprise! This behavior is intentional, but it can lead to subtle, head‑scratching bugs if you’re not expecting it. The safe pattern is: def add_item(item, container=None): if container is None: container = [] container.append(item) return container Why This Bug Doesn’t Happen in C# or C++ One thing I appreciate about strongly typed languages is how their design choices prevent entire categories of bugs. C# C# requires that default parameters be compile‑time constants: numbers, strings, enums, null You cannot use a mutable object as a default: void Foo(List<int> xs = new List<int>()); // ❌ compile error This rule completely eliminates Python’s shared‑mutable‑default issue. C++ C++ also avoids the problem, but for a different reason. Default arguments in C++ are compile‑time expressions, and they are substituted at the call site, not stored in the function object. This is allowed: void foo(const std::vector<int>& v = std::vector<int>()); // ✔ OK But the key detail is: a new temporary object is created every time the function is called. So there’s no shared state, and no Python‑style surprise. Takeaway Python’s flexibility is powerful, but it comes with sharp edges. C# and C++ take a stricter, compile‑time‑driven approach that prevents this entire class of bugs. If you’re writing Python APIs or utilities, it’s worth double‑checking your default parameters. A tiny detail can lead to some very unexpected behavior.
Python Default Parameter Pitfall: Shared Mutable State
More Relevant Posts
-
uv for Node Refugees: Python Tooling That Actually Makes Sense If you’re coming from the Node/TypeScript world, your first look at the Python ecosystem probably induced a panic attack. pip, poetry, venv, conda, pyenv it’s a fragmented mess of tools that all hate each other. Enter uv. It’s written in Rust (because of course it is), it’s ludicrously fast, and it finally drags Python tooling into the modern era. The deeply confusing part? I look around at open source repos and work projects, and nobody is using this yet. It is astonishing. We are still clinging to conda like a bad habit. I hate conda. I hate it from my gut. I hate the dependency resolver that takes long enough to brew a coffee. I hate the corrupted environments. I hate the sheer weight of it. uv is right here. It solves the problem. It is instant. Why are we still doing this to ourselves? The Rosetta Stone (Node → uv) Stop trying to memorize pip flags. Just map your existing brain damage to the new syntax: npm / pnpm → uv (The god tool) package.json → pyproject.toml (Metadata & deps) package-lock.json → uv.lock (Actually deterministic now) node_modules/ → .venv/ (Yes, it handles the venv for you) npm install <pkg> → uv add <pkg> npx <tool> → uvx <tool> nvm → uv python (Manages Python versions automatically) The "I Just Want to Code" Workflow Stop manually activating virtual environments. It’s 2026. 1. Start a project: uv init my-app cd my-app 2. Add dependencies (updates the lockfile and env automatically): uv add fastapi uv add --dev ruff pytest 3. Run stuff: # Don't source .venv/bin/activate like a caveman. uv run python app.py uv run pytest The "Don't Break Prod" Rule In Node, you use npm ci so you don't accidentally upgrade a library and take down production. In uv, you use locked mode. # In CI/CD pipelines uv sync --locked Summary uv stops Python development from feeling like archeology. It manages the runtime, the dependencies, and the environment in one go. If you are starting a new ML repo or a script, just use uv. Your future self (and your CPU fan) will thank you.
To view or add a comment, sign in
-
Python devs: Meet Ruff the Rust powered linter & formatter blazing through your code at warp speed! Python tooling is evolving FAST, thanks to Astral (makers of UV, which we geeked out over before). Ruff integrates seamlessly into your workflows – let's dive in. 1. Quick Setup Super simple: - Via UV: `uv tool install ruff@latest` (blazing speed, naturally). - Or curl the script: `curl -LsSf https://lnkd.in/gkuyfASH | sh` - PowerShell: `powershell -c "irm https://lnkd.in/gFkkKFhi | iex"` Lets Get Hands on: 1. Lint Like a Pro Check a file: `ruff check main.py` or Multiple files / Nested ones in current directory `ruff check .` - Spots unused imports/variables, syntax violations, and more – with clear error lines, rule codes, and fixes. Auto-fix safe issues: `ruff check --fix main.py` (Handles unused imports, extra spaces – without breaking functionality.) 2. For Big Projects (SaaS-scale) Scan everything: `ruff check .` Preview changes like Git diff *before* applying: `ruff check --fix --diff .` Example output: (-) import datetime (+) import time - Here output shows the file difference (Before vs After) as datetime import was shown as removed due to its unused case and only kept time import Review, approve, commit confidently – no blind trust! 3. Live Watching - `ruff check --watch .` : Ruff monitors your dir in real-time, flagging issues as you code. Catch bugs before they hit production (Python's runtime quirks, beware!). 4. Formatting Magic - `ruff format .` : Applies consistent Python style: even spaces, no junk tabs/newlines, clean functions. Makes code readable, maintainable, and team-friendly – across thousands of lines. Pro Tip: Always `ruff check --fix` then `ruff format` to avoid reformatting conflicts. That’s it , A quick overview of this powerful tooling CLI that Is actively into development and adopted by big projects around the world. Show some love on this tool and integrate it into GitHub Actions/CI to slash pipeline times and ship clean code. We have just scratched the surface, there is much more under the hood. try it out!
To view or add a comment, sign in
-
-
### Master Python's input() Function: Make Your Programs Interactive! 💻 This is a fundamental concept for anyone looking to build interactive and user-friendly applications. Key Learnings & Why It Matters: Enables User Interaction : The input() function allows your Python programs to pause and receive data directly from the user during execution. This is essential for building dynamic programs. Example: Imagine a game asking for your character's name: python player_name = input("Enter your hero's name: ") print(f"Welcome, {player_name}!") Program Flow Control : When input() is called, your program waits for the user to type something and press Enter. No further code will execute until input is provided, ensuring your program responds to user commands. How it feels: The program "freezes" at the input line until you press Enter. Crucial Data Type Rule: It's Always a String! : This is a major takeaway! Any data entered via input() is read as a string by default, even if it's a number. Example: If you input 5 into num = input(), Python sees it as the text "5". So, print(num + num) would output 55, not 10! Pro Tip: If you need to perform calculations, remember to type-cast the input to an integer (int()) or float (float()). python age_str = input("Enter your age: ") # User inputs 30 ageint = int(agestr) print(f"Next year you will be {age_int + 1}!") # Outputs "Next year you will be 31!" Enhance User Experience with Prompts : Don't leave your users guessing! Add clear, descriptive messages inside the input() function. This makes your program intuitive and easy to use. Example: city = input("Which city are you from? ") is much better than just city = input(). Handling Multiple Inputs : Learn how to prompt the user for multiple pieces of information, allowing for complex data collection and processing within your programs. Example: python num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) total = num1 + num2 print(f"The sum is: {total}") 💡 Homework Challenge : The video concludes with a great challenge: Write a Python program that takes a student's name and marks for three subjects, then calculates and displays their total percentage. A perfect way to practice what you've learned! --- #Python #PythonTutorial #InputFunction #Programming #Coding #BeginnerFriendly #InteractivePrograms #SoftwareDevelopment #TechSkills
To view or add a comment, sign in
-
Python Study Day 3 *Input and Output in Python - Input from the User: In Python, we use the input() function to take input from the user. The data entered by the user is always received as a string, so if you want to use it as a different data type (e.g., integer or float), you'll need to convert it using type conversion functions like int() or float(). name = input("Enter your name: ") age = int(input("Enter your age: ")) # Convert input to integer - Output to the Console: The print() function is used to display output to the console. You can use it to display text, variables, or results of expressions. print("Hello, " + name + "! You are " + str(age) + " years old.") You can also use f-strings (formatted string literals) for more readable code: print(f"Hello, {name}! You are {age} years old.") - Comments in Python Comments are ignored by the Python interpreter and are used to explain the code or leave notes for yourself or others. They do not affect the execution of the program. Single-line comments start with #: # This is a single-line comment print("Hello, World!") Multi-line comments can be written using triple quotes (""" or '''). These are often used to write detailed explanations or temporarily block sections of code: """ This is a multi-line comment. It can span multiple lines. """ print("Hello, Python!") - Escape Sequences Escape sequences are special characters in strings that start with a backslash (\). They are used to represent certain special characters. Some commonly used escape sequences: \n: New line \t: Tab space \\: Backslash Example: print("Hello\n World") # Output: # Hello # World print("Hello\t Python") # Output: Hello Python
To view or add a comment, sign in
-
Tutorial on Python's Conditional Statements (If-Else) In Python allow your program to make decisions and execute specific blocks of code based on whether a given condition evaluates to True or False. They are fundamental for controlling the flow of a program and handling different inputs or scenarios. ### 1. If Statement (2:45) Purpose: The if statement is used to test a single condition and execute a block of code only if that condition evaluates to True. If the condition is False, the code block associated with the if statement is skipped, and nothing is executed. Syntax: python if condition: # Code to be executed if the condition is True Important Points: The code inside the if block must be indented. This indentation is crucial for Python to understand the code structure. Conditions typically involve comparison operators (e.g., > , < , == ) which return a True or False boolean value. Example: python age = 26 if age > 19: print("You are an adult.") # Output: You are an adult. If age was 15, there would be no output. ### 2. If-Else Statement Purpose: The if-else statement provides an alternative block of code to execute if the if condition is False. This ensures that something happens regardless of whether the initial condition is true or false, avoiding empty outputs. Syntax: python if condition: # Code to be executed if the condition is True else: # Code to be executed if the condition is False Important Points: The else block does not require a condition because it automatically executes when the if condition is false. Example: python temperature = 30 if temperature < 25: print("It's a cool day!") else: print("It's a hot day!") # Output: It's a hot day! (since 30 is not less than 25) ### 3. If-Elif-Else Statement Purpose: This statement allows for checking multiple conditions sequentially. It provides a way to handle more complex scenarios where there are several possible outcomes based on different conditions. Python checks conditions from top to bottom, executing the code block for the first True condition it encounters. Syntax: python if condition1: # Code if condition1 is True elif condition2: # Code if condition2 is True (and condition1 was False) else: # Code if all preceding conditions were False Important Points: You can have multiple elif blocks. The else block is optional but provides a fallback for all cases where no if or elif condition is met. Example: python marks = int(input("Enter your marks (out of 100): ")) if marks >= 90: print("Grade A+") elif marks >= 80: print("Grade A") elif marks >= 70: print("Grade B") else: print("Grade C") # Example Input: 77 --> Output: Grade B # Example Input: 91 --> Output: Grade A+ #Python #Programming #ConditionalStatements #IfElse #Coding #TechEducation Continue..
To view or add a comment, sign in
-
📘 Day 6 – Control Statements in Python (Beginner Friendly 🚀) Control statements are like traffic signals 🚦 in a program. 👉 They control the flow (execution) of a program 👉 They decide what to run, when to run, and how many times to run There are 3 Types of Control Statements: 1️⃣ Conditional Statements 2️⃣ Looping Statements 3️⃣ Jumping Statements 1️⃣ Conditional Statements (Decision Making) 👉 Used when we want the program to make a decision. 🔹 if statement Runs code only if condition is True. age = 18 if age >= 18: print("You can vote") 🧠 Like telling a child: "If you finish homework → I give chocolate 🍫" 🔹 if else If condition is True → do this Else → do something else age = 16 if age >= 18: print("You can vote") else: print("You cannot vote") 🔹 if elif else Used when checking multiple conditions. marks = 75 if marks >= 90: print("Grade A") elif marks >= 60: print("Grade B") else: print("Grade C") 👉 Program checks one by one. 🔹 Nested if if inside another if. age = 20 citizen = True if age >= 18: if citizen: print("Eligible to vote") 👉 First check age 👉 Then check citizen 2️⃣ Looping Statements (Repeat Again & Again 🔁) Loops are used when we want to repeat something. 🔹 for loop Used when we know how many times to repeat. for i in range(5): print("Hello", i) 👉 Prints 5 times 🔹 while loop Runs until condition becomes False. count = 1 while count <= 5: print(count) count += 1 👉 Runs while condition is True 3️⃣ Jumping Statements (Stop or Skip 🚀) Used inside loops. 🔹 break Stops the loop completely. for i in range(10): if i == 5: break print(i) 👉 Loop stops when i = 5 🔹 continue Skips current iteration. for i in range(5): if i == 2: continue print(i) 👉 Skips 2 🔹 pass Does nothing (placeholder). for i in range(3): pass 👉 Used when writing future code. 🎯 Simple Summary 💡 Real Life Understanding Control statements = Brain of program 🧠 Without control → program runs blindly With control → program becomes smart visualization image think it also if understand i post image also more information follow Prem chandar #Python #PythonLearning #CodingForBeginners #SoftwareDeveloper #ControlStatements #LearnPython #TechCareer #ProgrammingBasics #linkedin #social media #brand #network #social media#student
To view or add a comment, sign in
-
-
𝗙𝗿𝗼𝗺 𝗢𝗻𝗲 𝗙𝗶𝗹𝗲 𝘁𝗼 𝗠𝗮𝗻𝘆: 𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗣𝘆𝘁𝗵𝗼𝗻 𝗖𝗼𝗱𝗲 𝗢𝗿𝗴𝗮𝗻𝗶𝘇𝗮𝘁𝗶𝗼𝗻 🐍 When you start learning Python, everything lives in one file. It works—until it doesn’t. As projects grow, a single script becomes hard to manage, debug, and reuse. The solution? Organizing your code using 𝗺𝗼𝗱𝘂𝗹𝗲𝘀 and 𝗽𝗮𝗰𝗸𝗮𝗴𝗲𝘀. Here’s the simple evolution every Python developer goes through: 1️⃣ 𝗦𝗰𝗿𝗶𝗽𝘁 → 𝗧𝗵𝗲 𝗦𝘁𝗮𝗿𝘁𝗶𝗻𝗴 𝗣𝗼𝗶𝗻𝘁 A script is a .𝗽𝘆 file you run directly. It performs a specific task, but its logic stays trapped in that file. This limits 𝘀𝗰𝗮𝗹𝗮𝗯𝗶𝗹𝗶𝘁𝘆 and 𝗿𝗲𝘂𝘀𝗲. 2️⃣ 𝗠𝗼𝗱𝘂𝗹𝗲 → 𝗥𝗲𝘂𝘀𝗮𝗯𝗹𝗲 𝗕𝘂𝗶𝗹𝗱𝗶𝗻𝗴 𝗕𝗹𝗼𝗰𝗸 A module is also a .𝗽𝘆 file—but designed to be imported into other programs. 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀: • Reuse functions without copy-pasting • Keep logic separated and clean • Avoid variable conflicts using private namespaces 𝗣𝗿𝗼 𝘁𝗶𝗽: Use 𝗶𝗳 __𝗻𝗮𝗺𝗲__ == "__𝗺𝗮𝗶𝗻__": to make a file work as both a script and a reusable module. 3️⃣ 𝗣𝗮𝗰𝗸𝗮𝗴𝗲 → 𝗢𝗿𝗴𝗮𝗻𝗶𝘇𝗶𝗻𝗴 𝗠𝘂𝗹𝘁𝗶𝗽𝗹𝗲 𝗠𝗼𝗱𝘂𝗹𝗲𝘀 A package is a folder containing related modules and an __𝗶𝗻𝗶𝘁__.𝗽𝘆 file. Think of it like folders on your computer—grouping related functionality together. 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲: project/ │ ├── main.py ├── data_processing.py ├── visualization.py └── utils/ ├── __init__.py └── helpers.py 4️⃣ 𝗪𝗵𝘆 𝗧𝗵𝗶𝘀 𝗠𝗮𝘁𝘁𝗲𝗿𝘀 (𝗥𝗲𝗮𝗹 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀) ✔ 𝗥𝗲𝘂𝘀𝗮𝗯𝗶𝗹𝗶𝘁𝘆 — Write once, use anywhere ✔ 𝗠𝗮𝗶𝗻𝘁𝗮𝗶𝗻𝗮𝗯𝗶𝗹𝗶𝘁𝘆 — Easier to debug and update ✔ 𝗦𝗰𝗮𝗹𝗮𝗯𝗶𝗹𝗶𝘁𝘆 — Essential for large projects ✔ 𝗣𝗿𝗼𝗳𝗲𝘀𝘀𝗶𝗼𝗻𝗮𝗹 𝘀𝘁𝗮𝗻𝗱𝗮𝗿𝗱𝘀 — Used in real-world systems 5️⃣ 𝗜𝗺𝗽𝗼𝗿𝘁 𝗕𝗲𝘀𝘁 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝘀 • 𝗶𝗺𝗽𝗼𝗿𝘁 𝗺𝗼𝗱𝘂𝗹𝗲 → Clean and clear • 𝗶𝗺𝗽𝗼𝗿𝘁 𝗺𝗼𝗱𝘂𝗹𝗲 𝗮𝘀 𝗮𝗹𝗶𝗮𝘀 → Short and readable • Avoid 𝗳𝗿𝗼𝗺 𝗺𝗼𝗱𝘂𝗹𝗲 𝗶𝗺𝗽𝗼𝗿𝘁 * → Causes confusion 𝗞𝗲𝘆 𝗜𝗻𝘀𝗶𝗴𝗵𝘁: Moving from scripts → modules → packages is the shift from writing code to building systems. This is the foundation behind powerful libraries like Pandas, NumPy, and every professional Python application. If you're learning Python, mastering code organization early will make you faster, cleaner, and more professional. #Python #Programming #DataScience #SoftwareDevelopment #CodingBestPractices #LearnPython #DataAnalytics
To view or add a comment, sign in
-
Is your Python code hiding "silent killers"? Python is the industry standard for data science and AI development, but its impressive speed is powered by a hidden engine: C-extensions. Libraries like NumPy, TensorFlow, and SciPy rely on C to handle the heavy lifting. However, there’s a catch. When C code fails, it doesn’t just throw a Python Exception. It triggers a Segmentation Fault that kills the entire Python interpreter. This can be a real nightmare for developers building automated testing pipelines. To address this, fascinating new research on Fault Detection for C-Extended Python Projects evolved Pynguin, a well-known automated testing tool, to handle these fatal crashes head-on. 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 𝗪𝗵𝗲𝗻 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 𝗛𝗶𝘁𝘀 𝗮 𝗧𝗲𝗿𝗺𝗶𝗻𝗮𝗹 𝗪𝗮𝗹𝗹 Typically, Pynguin generates thousands of tests and runs them all in the same process. But if it runs into an edge-case input that causes a C-extension to SegFault, the crash takes down the testing tool itself. This means the test generation stops, leaving the rest of the codebase completely untested. 𝗧𝗵𝗲 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: 𝗦𝘂𝗯𝗽𝗿𝗼𝗰𝗲𝘀𝘀 "𝗦𝗮𝗻𝗱𝗯𝗼𝘅𝗶𝗻𝗴" Researchers revamped Pynguin to utilize Subprocess-Execution. Instead of running tests in shared threads, the new version of Pynguin sends each test into its own isolated subprocess (a sandbox). If a C-extension faults, it only takes out the sandbox. The main testing tool continues to function, records the exact input that caused the crash, and moves on to the next test. 𝗧𝗵𝗲 𝗥𝗲𝘀𝘂𝗹𝘁𝘀 The researchers put this upgraded tool to the test on 1,648 modules across 21 large open-source libraries. Since the tool no longer self-destructs at the first fatal error, the results were astounding: • It successfully tested 56.5% more modules that were previously impossible to evaluate. • It automatically captured 213 unique crash causes. • It uncovered 32 zero-day bugs in major libraries that developers overlooked. If you’re building high-performance AI systems or backend infrastructure, check out the full research paper here to see how they pulled it off: tinyurl.com/3zvcupu9.
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development