yield is one of those Python keywords that looks simple until someone asks you to explain it. Most developers can tell you a function with yield in it produces values and works in for loops. Fewer can explain why that same function doesn't actually run when you call it. Turns out, that's the whole point. Generators (functions with yield) are functions that pause mid-execution and resume exactly where they left off: local variables, loop counters, everything intact. In my Python Context Managers series, I'm covering generators as a dedicated article because they are not a standalone concept. They are the engine behind @contextmanager, a cleaner way to build context managers in Python. You can't fully understand one without understanding the other. This article is a deep dive into generator functions: https://lnkd.in/dSNegaWK A function that remembers where it left off changes everything. #Python #SoftwareEngineering #Backend #Programming #WebDevelopment #BuildBreakLearn
Understanding Python Generators: The Engine Behind Context Managers
More Relevant Posts
-
Python: 06 🐍 Python Tip: Master the input() Function! Ever wondered how to make your Python programs interactive? It all starts with taking input from the user! ⌨️ 1) How to capture input? -To get data from a user, we have to use the input() function. To see it in action, you need to write in the terminal using: '$ python3 app.py' 2) The "Type" Trap 🔍 -By default, Python is a bit picky. If you want to know the type of our functions, You can verify this using the type() function: Python code: x = input("x: ") print(type(x)) Output: <class 'str'> — This means 'x' is a string! 3) Converting Types (Type Casting) 🛠️ If you want to do math, you have to convert that string into an integer. Let's take a look at this example- Python code: x = input("x: ") y = int(x) + 4 # Converting x to an integer so we can add 4! [Why do this? Without int(), here we called int() function to detect the input from the user, otherwise Python tries to do "x" + 4. Since you can't add text to a number, your code would crash! 💥] print(f"x is: {x}, y is {y}") The Result 🚀: If you input 4, the output will be: ✅ x is: 4, y is: 8 Happy coding! 💻✨ #Python #CodingTips #Programming101 #LearnPython #SoftwareDevelopment
To view or add a comment, sign in
-
-
Most Python code works. That’s not the problem. The problem is - most of it doesn’t scale past the person who wrote it. You’ve probably seen code like this: • full of comments explaining what’s happening • try/finally blocks everywhere • repeated logic for caching, logging, auth • functions doing 5 things at once It works. Until it doesn’t. The shift that changed how I think about Python: 👉 Stop writing logic 👉 Start using language-level patterns Once you start seeing it this way: • with replaces cleanup logic • decorators replace repeated behavior • generators replace unnecessary data structures • dunder methods make your objects feel native The result? Code that explains itself without comments, removes entire classes of bugs, and actually scales across teams. I wrote a deep dive on this - not surface-level tips, but how these patterns actually work, when to use them, and how they reshape your code. 👉 Read the full article: https://lnkd.in/g_9GZDRk Curious — what’s one Python concept that only clicked after real-world experience? For me, it was realizing generators aren’t about syntax - they’re about thinking in streams instead of collections. #Python #CleanCode #SoftwareEngineering #ScalableSystems #DesignPatterns #AdvancedPython #BackendDevelopment
To view or add a comment, sign in
-
Excited to share a new article I wrote for AppSignal. I wrote about a problem many Python teams run into with Celery: ✅ Retries can make failed tasks look less serious than they really are. ✅ The real exception path is often harder to follow than it should be. ✅ Debugging usually means going through worker logs to piece together what happened. ✅ That delay makes background job failures harder to catch early. In the article, I break down: ✅ Where Celery’s defaults create visibility gaps. ✅ Why retries can make failure tracking messy. ✅ What this looks like in real Python applications. ✅ How AppSignal improves visibility by surfacing failures, retries, and task context more clearly. Here’s the article: https://lnkd.in/d_XgE3g9 #Python #Celery #BackendEngineering #Observability #DevOps #TechnicalWriting
To view or add a comment, sign in
-
Your Python app can look healthy while background jobs are quietly failing. That's the problem with Celery by default. A task can fail, retry, and eventually succeed, while the real issue stays buried in worker logs. From the outside, everything looks fine. Until a user asks why something never happened. Nehemiah Bosire shows how to use AppSignal to track Celery task failures with full context, so you can see retries, exceptions, and patterns before they turn into bigger problems 👇 https://lnkd.in/eiHrDFCc
To view or add a comment, sign in
-
Day 16 / 30 - while Loops in Python What is a while Loop? A while loop keeps running its block of code as long as a condition is True. Unlike a for loop which runs a fixed number of times, a while loop runs an unknown number of times, it stops only when the condition becomes False. Perfect for situations where you don't know in advance how many repetitions you'll need. Syntax Breakdown while condition: # runs as long as condition is True # must update something to eventually make condition False while --> checks the condition before every single run condition --> any expression that evaluates to True or False How It Works, step by step Python checks the condition at the top of the loop If True --> it runs the indented block of code Goes back to the top and checks the condition again Keeps repeating until the condition becomes False When False --> exits the loop and continues the program for Loop vs while Loop for loop 1. Use when you know how many times to repeat 2. Looping over a list, range, sequence while loop 1. Use when you don't know how many times 2. Keep going until a condition changes The Infinite Loop -Most Common Mistake If your condition never becomes False, the loop runs forever, freezing your program. Always make sure something inside your loop changes the condition like incrementing a counter or taking user input so the loop can eventually stop. break and continue break - stops the loop immediately, exits even if the condition is still True continue → skips the current iteration and jumps back to the condition check Both break and continue work in for and while loops. Code Example # Count from 1 to 5 count = 1 while count <= 5: print("Count: " + str(count)) count = count + 1 # break — stop early number = 0 while number < 10: if number == 5: break # stops loop at 5 print(number) number += 1 Key Learnings ☑ A while loop runs as long as its condition is True , checks before every iteration ☑ Always update something inside the loop, counter, input, or flag or you'll get an infinite loop ☑ break exits the loop immediately when a condition is met ☑ continue skips the current iteration and jumps back to the condition check ☑ Use for when you know the count — use while when you don't Why It Matters While loops power real systems — PIN verification, login retry limits, game loops, servers waiting for requests. Anywhere your program needs to wait or keep trying until something changes, a while loop is the answer. My Takeaway A for loop is like a to-do list — you know how many items there are. A while loop is like waiting for a bus — you keep waiting until it arrives. Different tools, different situations. #30DaysOfPython #Python #LearnToCode #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
If you work with Python, have you ever wondered: • What is a list comprehension really? • Is it just a shorter for loop? • When should I NOT use it? List comprehensions are not just syntactic sugar, they are a fundamental part of writing Pythonic code. And no, they are not just “shorter loops”. They express intent. That’s the key difference. Let’s look at a simple example: 𝗿𝗲𝘀𝘂𝗹𝘁 = [] 𝗳𝗼𝗿 𝘅 𝗶𝗻 𝗿𝗮𝗻𝗴𝗲(𝟭𝟬): 𝗿𝗲𝘀𝘂𝗹𝘁.𝗮𝗽𝗽𝗲𝗻𝗱(𝘅 * 𝟮) Now, the same code using list comprehension: 𝗿𝗲𝘀𝘂𝗹𝘁 = [𝘅 * 𝟮 𝗳𝗼𝗿 𝘅 𝗶𝗻 𝗿𝗮𝗻𝗴𝗲(𝟭𝟬)] Both do the same thing. But they are NOT the same. When you write: 𝗿𝗲𝘀𝘂𝗹𝘁 = [𝘅 * 𝟮 𝗳𝗼𝗿 𝘅 𝗶𝗻 𝗿𝗮𝗻𝗴𝗲(𝟭𝟬)] You are telling Python: “I am building a new list from an existing iterable”. That intention is explicit. Now, here is where things go wrong: [𝗽𝗿𝗶𝗻𝘁(𝘅) 𝗳𝗼𝗿 𝘅 𝗶𝗻 𝗿𝗮𝗻𝗴𝗲(𝟭𝟬)] This works, but it should not be written like this. Why? Because list comprehensions are meant to create data, not perform side effects. When you use them like this, you are creating a list you don’t need, hiding the real intention of the code, and making it less readable. Takeaway: “List comprehensions are not about writing less code. They are about writing code that clearly expresses transformation.” Use them when you are building data. Avoid them when you are executing actions. #python #listcomprehension #pythonic
To view or add a comment, sign in
-
✍️ New post introducing profiling-explorer, a tool for exploring Python profiling data (pstats files). Use it with the classic cProfile (now called profiling.tracing) or Python 3.15’s new sampling profiler, Tachyon (profiling.sampling). https://lnkd.in/eZ6D8ZMD #Python
To view or add a comment, sign in
-
🚀 Python GIL vs No-GIL: Real FastAPI Benchmarks (Python 3.13) Python is going through one of its biggest shifts in decades — the Global Interpreter Lock (GIL) is now optional in Python 3.13. But the real question is: 👉 Does removing the GIL actually improve real-world performance? A recent benchmark using FastAPI gives some interesting insights 👇 💡 Key Takeaways: 🔹 True parallelism is finally possible With the GIL removed, Python threads can run across multiple CPU cores — something that wasn’t possible before. 🔹 Massive gains for CPU-bound workloads In multi-threaded scenarios, performance can scale significantly (even 3–4x in some cases) when tasks are parallelizable. 🔹 FastAPI doesn’t magically get faster FastAPI is primarily async-based (single-threaded concurrency), so it doesn’t automatically benefit from no-GIL unless you switch to thread-based execution. 🔹 Trade-offs are real Single-thread performance can drop due to added locking overhead Many libraries (NumPy, Pandas, etc.) aren’t fully ready yet Thread-safety becomes your responsibility 🔹 Still experimental Free-threaded Python in 3.13 is not production-ready yet — but it’s a huge step forward. 🔥 What this means for developers: If you’re building CPU-heavy APIs, no-GIL could be a game changer If you rely heavily on async + I/O, impact will be limited The ecosystem still needs time to adapt 👉 Curious to hear your thoughts: Would you adopt no-GIL Python today, or wait for ecosystem stability? #Python #FastAPI #BackendDevelopment #Concurrency #Performance #SoftwareEngineering
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