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/VideosSampleCode
Closures video: https://www.youtube.com/watch?v=jXugs4B3lwU
Local vs global lookup video: https://www.youtube.com/watch?v=9v8eu4MOet8
SUPPORT ME โญ
---------------------------------------------------
Sign up on Patreon to get your donor role and early access to videos!
https://patreon.com/mCoding
Feeling generous but don't have a Patreon? Donate via PayPal! (No sign up needed.)
https://www.paypal.com/donate/?hosted_button_id=VJY5SLZ8BJHEE
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: https://discord.gg/Ye9yJtZQuN
Github: https://github.com/mCodingLLC/
Reddit: https://www.reddit.com/r/mCoding/
Facebook: https://www.facebook.com/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
188 Comments