Lambda in a Loop is a Code Smell

Published: 02 October 2023
on channel: mCoding
61,767
2.7k

Watch out for smelly code!

A common mistake in Python is to use a lambda function inside of a loop. While it's not always a problem, it should set off your senses to take a second look when you see a lambda inside a loop. If the lambda references a loop variable, you might not realize that the way that closures (or cell variables) work in Python means the lambda doesn't store the latest value of a variable that was present when the lambda is created. In this video I walk through a simplified real-world-code example where I made this mistake myself, including how to fix it.


― mCoding with James Murphy (https://mcoding.io)

Source code: https://github.com/mCodingLLC/VideosS...
Closures video:    • Functions within functions, closures,...  
Local vs global lookup video:    • Local and Global Variable Lookup Weir...  


SUPPORT ME ⭐
---------------------------------------------------
Sign up on Patreon to get your donor role and early access to videos!
  / mcoding  

Feeling generous but don't have a Patreon? Donate via PayPal! (No sign up needed.)
https://www.paypal.com/donate/?hosted...

Want to donate crypto? Check out the rest of my supported donations on my website!
https://mcoding.io/donate

Top patrons and donors: Jameson, Laura M, Dragos C, Vahnekie, Neel R, Matt R, Johan A, Casey G, Mark M, Mutual Information, Pi

BE ACTIVE IN MY COMMUNITY 😄
---------------------------------------------------
Discord:   / discord  
Github: https://github.com/mCodingLLC/
Reddit:   / mcoding  
Facebook:   / james.mcoding  

CHAPTERS
---------------------------------------------------
0:00 Intro
0:12 What is a code smell?
0:43 Sponsoring myself!
1:11 Example setup
2:49 The symptoms
4:02 Why the lambda in a loop is bad
5:00 The partial fix
5:59 Exceptions to the rule
7:15 Prevent this before it ever happens
8:00 Thanks


Watch video Lambda in a Loop is a Code Smell online without registration, duration hours minute second in high quality. This video was added by user mCoding 02 October 2023, don't forget to share it with your friends and acquaintances, it has been viewed on our site 61,767 once and liked it 2.7 thousand people.