r/badcode • • Apr 24 '21

python very efficient and scalable code

Post image
1.0k Upvotes

110 comments sorted by

View all comments

63

u/RoLoLoLoLo Apr 24 '21

Since it imports tkinter with *, ugh, but that's another story, the functions are probably used for controls without inputs (like simple buttons).

The first immediately obvious improvement is deduplicating and outsourcing all logic into a helper function chosetag(tag) and just calling the helper with the corresponding string.

The second improvement, which a lot of beginners don't realize, is the fact that they can skip making special functions for every button by just using a lambda expression in the parameters for their buttons. So instead of action=chosetagComedy you can just use action= lambda : chosetag('Comedy')

10

u/tuckmuck203 Apr 24 '21

is it a tkinter thing that makes you use a lambda? why can't you just call it directly with action=chosetag('Comedy')

26

u/Rektedekte Apr 24 '21

If you do that, it would assign action to the result of chosetag. It would execute it. The lambda wraps the chosetag call into another function, so that it can be used as a callback.

4

u/tuckmuck203 Apr 24 '21

Oh gotcha, that makes total sense. Probably would've figured it out if I'd tried it haha. Thanks for the explanation!