AI-generated Python code often has a "shared state" problem. Do you know where it's hiding? 🐍🔍 When reviewing Python, "it runs without errors" is the lowest possible bar. Because of Python's unique semantics, code can look perfectly logical while hiding architectural landmines that only manifest after multiple executions. In my latest AI Code Review session, we focused on the three "silent killers" frequently found in AI-generated Python snippets: ⚠️ 1. The Shared State Trap (Mutable Default Arguments) The most common bug: def log_event(name, log=[]). In Python, that empty list [] is created once at definition time, not every time the function is called. Every call shares the same object, leading to data leakage between unrelated requests. The Anchor: Look for [] or {} in function signatures—it's a massive red flag. 👣 2. The Iterator Trap (Mutation During Iteration) Modifying a list while looping over it—like calling list.remove(x) inside a for x in list: loop—causes the iterator to skip elements as the list shifts under its feet. The code won't crash; it will just silently produce incomplete results. The Anchor: Always verify if a loop is modifying its own source. If it is, use a list comprehension instead. 🔗 3. Final-Value Closures (Late-Binding Variables) AI models love creating lists of functions in loops: lambda: print(i). But Python captures the variable name, not its value at creation time. The result? Every function in your list will print the last value of the loop. The Anchor: Binding loop variables requires capturing them via default arguments: lambda idx=i: print(idx). The AI Reviewer's Perspective: LLMs are excellent at syntax, but they frequently fall for these three semantic "gotchas." As a reviewer (especially in RLHF tasks), your value lies in catching these subtle logic failures that simple test cases might miss. What’s your most "hated" Python gotcha? 👇 #Python #SoftwareEngineering #CodeQuality #AICodeReview #BugHunting #ProgrammingTips #CleanCode #RLHF #PromptEngineering IntelliForge Learning
3 Python Gotchas in AI-Generated Code
More Relevant Posts
-
🧠 Python Tricky Outputs — Test Your Knowledge! Can you guess the output of these three Python snippets? Let's find out! 👇 🔍 OUTPUTS: Snippet 1 → '['a', 'b', 'c', 'd', 'e', 'f,g,h']' Snippet 2 → '{2, 3}' Snippet 3 → '2' 🔍HOW IT WORKS: "Snippet 1 — split() with maxsplit=5" Step 1 → String: "a,b,c,d,e,f,g,h" Step 2 → Split by comma ',' Step 3 → maxsplit=5 means only split the first 5 times. Step 4 → Result has 6 items (5 splits + remainder) Split 1 → "a" Split 2 → "b" Split 3 → "c" Split 4 → "d" Split 5 → "e" Remainder → "f,g,h" (no more splitting) "Snippet 2 — Set Intersection (&)" Step 1 → {1, 2, 3} Step 2 → {2, 3, 4} Step 3 → & (ampersand) finds common elements. Step 4 → Common elements: 2 and 3 Step 5 → Result: {2, 3} "Snippet 3 — dict.get() with default" Step 1 → Dictionary d = {"a": 1} Step 2 → d.get("b", 2) Step 3 → "b" is NOT a key in the dictionary Step 4 → get() returns default value → 2 Step 5 → If the key existed, it would return the actual value ⚠️ EDGE CASES: "split() maxsplit" maxsplit=0 → No splitting → Entire string as one item maxsplit > number of commas → Splits all, extra maxsplit ignored Empty string → [''] "Set intersection" Empty set → {} No common elements → set() Same sets → Returns the set itself "dict.get()" Key exists → Returns actual value Key missing → Returns default No default provided → Returns None 📌 REAL-WORLD APPLICATIONS: "split() with maxsplit" → Parsing logs, CSV headers, first N fields only "Set intersection" → Finding common users, shared interests, mutual friends "dict.get()" → Safe dictionary access, avoiding KeyError, from defaults 💡 KEY CONCEPTS: • 'split(',', maxsplit)' → Maximum number of splits to perform • '&' operator → Set intersection (common elements) • 'dict.get(key, default)' → Returns default if key missing • No KeyError → Safer than dict[key] 📌 QUICK QUIZ — Test Yourself: # Q1: What's the output? print("one,two,three,four".split(',', 2)) # Q2: What's the output? print({5, 6, 7} & {6, 7, 8}) # Q3: What's the output? d = {"name": "Alice"} print(d.get("age", 25)) #Python #Coding #Programming #LearnPython #Developer #Tech #PythonTips #Dictionary #Sets #Strings #CodeQuiz #SplitMethod #SetOperations #GetMethod #Day76
To view or add a comment, sign in
-
-
🔎 Mastering f-Strings in Python #Day32 If you're learning Python, f-strings are something you’ll use almost every day. They make string formatting cleaner, faster, and much more readable. 🔹 What Are f-Strings? f-strings (formatted string literals) were introduced in Python 3.6 and provide a simple way to embed variables and expressions directly inside strings. You create them by placing f before the opening quotation marks. Syntax: f"Your text {variable_or_expression}" Example: name = "Ishu" age = 20 print(f"My name is {name} and I am {age} years old.") ✅ Output: My name is Ishu and I am 20 years old. 🔹 Why Use f-Strings? Before f-strings, we used: 1. % Formatting (Old Style) name = "Ishu" print("Hello %s" % name) 2. .format() Method print("Hello {}".format(name)) 3. f-Strings (Modern Way) ✅ print(f"Hello {name}") 💡Cleaner 💡Easier to read 💡Faster than older methods 💡Supports expressions directly 🔹 Inserting Variables product = "Laptop" price = 55000 print(f"The {product} costs ₹{price}") Output: The Laptop costs ₹55000 🔹 Using Expressions Inside f-Strings You can perform calculations directly inside {} a = 10 b = 5 print(f"Sum = {a+b}") print(f"Product = {a*b}") Output: Sum = 15 Product = 50 🔹 Calling Functions Inside f-Strings name = "ishu" print(f"Uppercase: {name.upper()}") Output: Uppercase: ISHU 🔹 Formatting Numbers Decimal Places pi = 3.14159265 print(f"{pi:.2f}") Output: 3.14 .2f → 2 decimal places. 🔹 Adding Commas to Large Numbers num = 1000000 print(f"{num:,}") Output: 1,000,000 🔹 Formatting Percentages score = 0.89 print(f"{score:.2%}") Output: 89.00% 🔹 Padding and Alignment Left Align print(f"{'Python':<10}") Right Align print(f"{'Python':>10}") Center Align print(f"{'Python':^10}") Useful for reports and tables. 🔹 Using Expressions with Conditions marks = 85 print(f"Result: {'Pass' if marks>=40 else 'Fail'}") Output: Result: Pass Yes — even conditional logic works 😎 🔹 Date Formatting with f-Strings from datetime import datetime today = datetime.now() print(f"{today:%d-%m-%Y}") Example output: 26-04-2026 🔹 Debugging with f-Strings (Awesome Feature) Python allows this: x = 10 y = 20 print(f"{x=}, {y=}") Output: x=10, y=20 Great for debugging 🛠️ 🔹 Escaping Curly Braces Need literal braces? print(f"{{Python}}") Output: {Python} Use double braces {{ }} 🔹 f-Strings with Dictionaries student = {"name":"Ishu","marks":95} print(f"{student['name']} scored {student['marks']}") Output: Ishu scored 95 🔹 f-Strings with Loops for i in range(1,4): print(f"Square of {i} is {i*i}") Output: Square of 1 is 1 Square of 2 is 4 Square of 3 is 9 🔹 Final Thoughts f-Strings are one of Python’s most elegant features. They make your code: ✔More readable ✔More powerful ✔More Pythonic ✔More professional #Python #DataAnalytics #PythonProgramming #DataAnalysis #DataAnalysts #PowerBI #Excel #CodeWithHarry #Tableau #SQL #Consistency #DataVisualization #DataCleaning #DataCollection #MicrosoftPowerBI #MicrosoftExcel #F_Strings
To view or add a comment, sign in
-
✅ *Top Python Basics Interview Q&A - Part 3* 🌟 *1️⃣ What are classes and objects in Python?* Classes are blueprints for creating objects. Objects are instances of classes with attributes and methods. ``` class Dog: def __init__(self, name): self.name = name def bark(self): return f"{self.name} says Woof!" my_dog = Dog("Buddy") print(my_dog.bark()) # Output: Buddy says Woof! ``` *2️⃣ What is inheritance in Python?* Inheritance allows a class (child) to inherit properties from another class (parent). ``` class Animal: def speak(self): return "Sound" class Cat(Animal): def speak(self): return "Meow" ``` *3️⃣ What are self and `__init__`?* self refers to the current instance. `__init__` is the constructor method called when creating objects. *4️⃣ Explain access modifiers (public, private, protected).* Python uses conventions: obj.attr (public), _obj_attr (protected), __obj_attr (private/name mangling). *5️⃣ What are Python packages?* Directories containing modules with an `__init__.py` file. Example: numpy, pandas. *6️⃣ How do you read/write files in Python?* Use open() with modes "r", "w", "a". Always use with statement for auto-closing. ``` with open("file.txt", "w") as f: f.write("Hello World") ``` *7️⃣ What is the difference between append() and extend()?* append() adds a single item. extend() adds multiple items from an iterable. *8️⃣ Explain *args and **kwargs.* *args passes variable positional arguments. **kwargs passes variable keyword arguments. ``` def func(*args, **kwargs): print(args, kwargs) func(1, 2, name="Abinash") # (1, 2) {"name": "Abinash"} ``` *9️⃣ What is a decorator?* A function that modifies another function's behavior. Uses @decorator syntax. *🔟 What is list slicing?* Extract portions of lists: list[start:stop:step]. ``` nums = [0,1,2,3,4] print(nums[1:4]) # [1, 2, 3] ```
To view or add a comment, sign in
-
✅ *Top Python Basics Interview Q&A - Part 3* 🌟 *1️⃣ What are classes and objects in Python?* Classes are blueprints for creating objects. Objects are instances of classes with attributes and methods. ``` class Dog: def __init__(self, name): self.name = name def bark(self): return f"{self.name} says Woof!" my_dog = Dog("Buddy") print(my_dog.bark()) # Output: Buddy says Woof! ``` *2️⃣ What is inheritance in Python?* Inheritance allows a class (child) to inherit properties from another class (parent). ``` class Animal: def speak(self): return "Sound" class Cat(Animal): def speak(self): return "Meow" ``` *3️⃣ What are self and `__init__`?* self refers to the current instance. `__init__` is the constructor method called when creating objects. *4️⃣ Explain access modifiers (public, private, protected).* Python uses conventions: obj.attr (public), _obj_attr (protected), __obj_attr (private/name mangling). *5️⃣ What are Python packages?* Directories containing modules with an `__init__.py` file. Example: numpy, pandas. *6️⃣ How do you read/write files in Python?* Use open() with modes "r", "w", "a". Always use with statement for auto-closing. ``` with open("file.txt", "w") as f: f.write("Hello World") ``` *7️⃣ What is the difference between append() and extend()?* append() adds a single item. extend() adds multiple items from an iterable. *8️⃣ Explain *args and **kwargs.* *args passes variable positional arguments. **kwargs passes variable keyword arguments. ``` def func(*args, **kwargs): print(args, kwargs) func(1, 2, name="Abinash") # (1, 2) {"name": "Abinash"} ``` *9️⃣ What is a decorator?* A function that modifies another function's behavior. Uses @decorator syntax. *🔟 What is list slicing?* Extract portions of lists: list[start:stop:step]. ``` nums = [0,1,2,3,4] print(nums[1:4]) # [1, 2, 3] ``` 💬 *Double Tap ❤️ for Part 4!*
To view or add a comment, sign in
-
🔸 🔸 🔸 Classic example to address late-binding and closures in python This 4 line of code talks about multiple important concepts ↘️ Code: funcs = [] for i in range(3): funcs.append(lambda : i) print([f() for f in funcs]) 🤔 What do you think ❓ Will it give any result, will it error out of random ❓ 🟰 Well, this prints [2,2,2] over console The idea is to demystify why this code does what it does under the hood. Concepts ↘️ ➡️ Is lambda : i a valid syntax ? If yes, what does it denote It denotes a shorthand notation to define a function that does not accept any input parameters and returns a single value as output. What will lambda : i resolve to ❓ ↘️ def f(): return i ❓ What is the iterative statement doing 🟰 It simply creates a container in memory, denoted by i. Initializes i to 0 and keeps incrementing the value that the container referenced by i contains ➡️ i : 0 -> 1 -> 2 ❓What will the list funcs hold ➡️ It's important to note here, funcs is a list that appends lambda into it. ➡️ Since, lambda is nothing more than a function in python, the list holds function ✅ ❓ But, how can a list hold function and what does it mean ➡️ Python treats function as objects, and in programming objects are nothing more than a memory address. 🟰 So, the funcs list holds memory addresses that individually resolve to functions denoted by lambda ✅ ➡️ Another important pointer to note here , the list holds the memory reference to these functions, not the actual value returned by the function. ✅ ❓ Demistify [f() for f in funcs] 🟰 This is a list comprehension in python. ➡️ We are iterating over all thats contained in the list, referencing each element via local variable f Since, f refers to an in-memory function, f() will simply invoke the function call. ✅ ➡️ When i = 0: Invoke f(), the first function pointed to by the first element of the list funcs ❓ The interesting part Function call always creates a new individual scope in python. You can say it as a standalone local environment specific to that function call. So, for the first element in funcs f() -> invokes a function that returns i ❓ Where is i now ➡️ Well, i comes from the loop scope created earlier and is used in the enclosed scope lambda : i denoted by function. ❓ So , are we talking about a closure concept in python here ? ➡️ Yes, this is a closure as lambda is closing over the variable i which is defined in the outer scope, the outer scope is the loop scope. ❓ Another interesting thing to note here is : ➡️ i is defined over a single outer scope, so it is shared amongst all the functions contained in the list funcs. 🤔 Think of it as : We are evaluating each function in the list funcs, where each function simply returns i. 🟰 The value of i = 2, post loop iteration finished in range(3), and hence each of these function calls will return the value 2 i.e. value of the variable closed over by lambda. #python #closure #lambda #softwareengineering #dataengineering
To view or add a comment, sign in
-
Task Holberton Python: Mutable vs Immutable Objects During this trimester at Holberton, we started by learning the basics of the Python language. Then, as time went on, both the difficulty and our knowledge gradually increased. We also learned how to create and manipulate databases using SQL and NoSQL, what Server-Side Rendering is, how routing works, and many other things. This post will only show you a small part of everything we learned in Python during this trimester, as covering everything would be quite long. Enjoy your reading 🙂 Understanding how Python handles objects is essential for writing clean and predictable code. In Python, every value is an object with an identity (memory address), a type, and a value. Identity & Type x = 10 print(id(x)) print(type(x)) Mutable Objects Mutable objects (like lists, dicts, sets) can change without changing their identity. lst = [1, 2, 3] lst.append(4) print(lst) # [1, 2, 3, 4] Immutable Objects Immutable objects (like int, str, tuple) cannot be changed. Any modification creates a new object. x = 5 x = x + 1 # new object Why It Matters With mutable objects, changes affect all references: a = [1, 2] b = a b.append(3) print(a) # [1, 2, 3] With immutable objects, they don’t: a = "hi" b = a b += "!" print(a) # "hi" Function Arguments Python uses “pass by object reference”. Immutable example: def add_one(x): x += 1 n = 5 add_one(n) print(n) # 5 Mutable example: def add_item(lst): lst.append(4) l = [1, 2] add_item(l) print(l) # [1, 2, 4] Advanced Notes - Shallow vs deep copy matters for nested objects - Beware of aliasing: matrix = [[0]*3]*3 Conclusion Mutable objects can change in place, while immutable ones cannot. This impacts how Python handles variables, memory, and function arguments—key knowledge to avoid bugs.
To view or add a comment, sign in
-
Three months ago, our agent cited Python 3.13 as the latest stable release in a research report. It was wrong — 3.12 was current at the time. The factcheck caught it. Corrected the report. That part isn't remarkable. Any review process would catch that. What happened next is the part that matters: the agent stored a lesson. Not the corrected fact — the lesson about the mistake itself. "Always verify version numbers against the official release page. Don't rely on training data for anything with a release cycle." Two weeks later, I asked it to research a completely different tool. The vector memory surfaced that lesson during pre-search. The agent went straight to the official changelog before writing a single sentence about version compatibility. Nobody told it to. It remembered why it had been wrong before. This is the self-improvement loop I've been building toward in this series. Previous posts covered the infrastructure — four memory types, four storage systems, routing, retrieval. This post is about what it enables: an agent that gets better without being retrained. The loop: 1. Agent produces output 2. Factcheck or human review finds an error 3. The correction gets saved — not just the right answer, but the lesson: what went wrong and how to avoid it 4. Next time, pre-search surfaces the lesson before the agent starts working The key word is "lesson." We don't store "Python 3.12 is correct." We store "version numbers from training data are unreliable — always check the source." One is a fact that expires. The other is a behavior that compounds. The same loop runs on human feedback. I told the agent: "Don't mock the database in integration tests." Instead of losing that correction after the session, the agent saved it with structure — what was corrected, why it was wrong, how to apply it in the future. That's a feedback memory. Next time it writes integration tests — in any project, any session — it retrieves the lesson and applies it. Over time, these accumulate into working knowledge about how to do the job correctly. Does it work? In the first 20 research sessions, the agent averaged 3.2 factcheck corrections per report. After 80+ sessions with the lesson loop: 0.8. Not zero. But the same category of mistake rarely happens twice. Version numbers, citation formats, API accuracy — each corrected once, stored as a lesson, applied going forward. No fine-tuning, no retraining. The model is the same. The memory layer is what improved. The deeper insight: the agent doesn't just store information. It stores lessons about how to handle information. Facts expire. Lessons compound. What's the most repeated mistake your agent makes — the one you keep correcting but it never sticks? #AIAgents #AgentArchitecture #SelfImprovingAI
To view or add a comment, sign in
-
📘 Python for PySpark Series – Day 15 🎭 Polymorphism in Python ✨ What is Polymorphism? Polymorphism means “many forms”. It allows the same method or function to behave differently based on the object. ➡️ Promotes flexibility and dynamic behavior in code 🔹 Why Polymorphism? ✔ Improves code flexibility ✔ Reduces complexity ✔ Enhances readability ✔ Supports method reusability 🔹 Types of Polymorphism ✔ Method Overriding (Runtime) ✔ Method Overloading (Compile-time – limited in Python) ✔ Operator Overloading 🔹 Syntax (Method Overriding) class Parent: def show(self): print("Parent method") class Child(Parent): def show(self): print("Child method") 🔹 Example class Animal: def sound(self): print("Some sound") class Dog(Animal): def sound(self): print("Bark") class Cat(Animal): def sound(self): print("Meow") animals = [Dog(), Cat()] for a in animals: a.sound() ➡️ Same method sound() → different outputs 🔗 Why Polymorphism in PySpark? ✔ Same operations work on different data types (RDD, DataFrame) ✔ Functions behave differently based on input ✔ Helps in writing generic and reusable code 🏫 Real-Life Analogy (Remote Control 📺) One remote → multiple devices ➡️ Same button (action) → different behavior (TV, AC, etc.) 🧠 Interview Key Points ✔ Polymorphism = one interface, multiple implementations ✔ Achieved using method overriding ✔ Supports dynamic method dispatch ✔ Increases flexibility and scalability 🧠 Key Takeaway Polymorphism allows writing flexible and reusable code where the same operation behaves differently for different objects. 🔖 Hashtags #python #pyspark #dataengineering #oop #polymorphism #pythonbasics #learningjourney #coding
To view or add a comment, sign in
-
-
#Understanding Python Destructors: A Practical Mini-Project # Python’s __init__ method gets all the spotlight, but what happens when an object’s job is done? That’s where the Destructor (__del__) comes in. I recently explored how to use destructors to manage external resources efficiently. Here is a mini-project demonstrating a Smart File Session Manager. 🛠️ The Project: Automated Resource Cleanup In real-world apps, forgetting to close a file or a database connection can lead to memory leaks. This script ensures that the resource is safely closed the moment the object is destroyed. 📝 Step-by-Step Implementation: Step 1: Define the Class and Constructor We initialize the session and automatically create a log file. Python class SessionManager: def __init__(self, name): self.name = name self.file = open(f"{self.name}.txt", "w") print(f"✅ Session '{self.name}' started and file created.") Step 2: Add Functionality A simple method to write logs to our file. Python def write_log(self, message): self.file.write(message + "\n") print(f"✍️ Logged: {message}") Step 3: Implement the Destructor (__del__) This is the magic part. It triggers automatically when the object is deleted or the program ends. Python def __del__(self): self.file.write("Session Closed.\n") self.file.close() print(f"🗑️ Destructor Called: Resources for '{self.name}' cleaned up.") Step 4: Execute and Observe Python # Creating the object session = SessionManager("User_Activity_Log") session.write_log("User logged in at 10:00 AM") # Manually deleting the object to trigger the destructor del session 💡 Key Takeaways: Automatic Cleanup: The __del__ method ensures that even if you forget to close a file, Python handles it during garbage collection. Resource Management: Great for handling database connections, network sockets, or temporary files. Caution: While powerful, destructors should be used carefully due to how Python's Garbage Collector handles circular references. Building these small utility projects helps in understanding the "under the hood" mechanics of Python. How do you handle resource cleanup in your projects? Do you prefer Destructors or Context Managers (with statements)? Let’s discuss in the comments! 👇 #Python #Programming #SoftwareDevelopment #CleanCode #CodingTips #PythonBeginner #BackendDevelopment
To view or add a comment, sign in
Explore related topics
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
Next 🎚️!