AVOID Making "THIS Stupid Mistake" In Python (It's bad)

  Рет қаралды 16,956

Indently

Indently

Жыл бұрын

Avoid making this stupid mistake in Python. It's can be really hard to catch when your projects become bigger, so it's good just to avoid it immediately.
▶ Become job-ready with Python:
www.indently.io
▶ Follow me on Instagram:
/ indentlyreels

Пікірлер: 70
@Indently
@Indently Жыл бұрын
As some of you kindly pointed out, I made a mistake in this video. Instead of checking: >> if not items Please use: >> if items is None The reason being that if you happen to pass in an empty list, the if block will still execute with "if not items" because an empty list is a "falsy value". While if you explicity check that the list is None, it will accurately create a new list if a list is not provided.
@lyrikalinyoswiminpoo
@lyrikalinyoswiminpoo Жыл бұрын
Boot camp or Self learning Python in 2023. Your advice?
@creed404
@creed404 Жыл бұрын
We still should check if we passed a list though 😅
@dragweb7725
@dragweb7725 4 ай бұрын
At least if we put the guard "if not items" and we pass any falsy value the guard will still handle it and correct it (we could pass in a {}, a 0 or whatever without having trouble)
@allo5668
@allo5668 Жыл бұрын
The problem with headlines like this is that when someone makes this mistake in my team it will be impossible to find this specific video when I search for it. I’ve had that problem before, where I searched “Indently import *” and nothing came up cuz the video was title “this is probably the worst mistake you can make”
@Indently
@Indently Жыл бұрын
Thank you for you feedback and I understand that completely. I get that a lot with my Shorts. I will try to keep the titles interesting while making them more searchable in the future :)
@SusanAmberBruce
@SusanAmberBruce Жыл бұрын
@@Indently Yes mate, you come across as a teacher, so we're not looking for clickbait init
@thebigboi5357
@thebigboi5357 Жыл бұрын
It also delegitimizes the video and makes it embarrassing to share with coworkers
@creed404
@creed404 Жыл бұрын
I don’t think so, cuz the title isn’t the only factor for videos recommendation, he still can put it in tags or the description
@NoidoDev
@NoidoDev 8 ай бұрын
Pylint finds the error.
@IlariVallivaara
@IlariVallivaara Жыл бұрын
The "fixed" implementation seems to be broken too because it does not check for None explicitly, but also replaces an empty list with a new instance. This gives it different and unexpected behavior when passing an empty and populated list, which is not what we want (passing empty lists migh be easily happening in real world software). Example: def adder(x, items=None): if not items: items = [] items.append(x) return items a = [] b = adder(1, a) c = [1, 2, 3] d = adder(4, c) print("a:", a) print("b:", b) print("c:", c) print("d:", d) This prints out: a: [] b: [1] c: [1, 2, 3, 4] d: [1, 2, 3, 4] Edit: For some reason did not see the pinned post. Sorry for redundancy.
@Indently
@Indently Жыл бұрын
Thanks for mentioning it and don't worry about the redundancy :)
@arthurs3058
@arthurs3058 Жыл бұрын
Exactly
@NickDanger3
@NickDanger3 Жыл бұрын
This looks more like a stupid feature of pythons implementation of default arguments, rather than a stupid mistake
@chasedunagan
@chasedunagan 7 ай бұрын
Watched this video 6 months ago. Made the exact same mistake 6 months later. Remembered this video and came back to watch how to fix it. Thanks!
@minhphamhoang2894
@minhphamhoang2894 Жыл бұрын
It is better to use if items is None rather than if not items
@Indently
@Indently Жыл бұрын
Very true, thank you.
@stevenbrown9185
@stevenbrown9185 Жыл бұрын
I can't believe people are nitpicking calling it a mistake, even going so far as to say that an editor shouldn't even alert the user to it. This feature of Python, while perhaps one that has a purpose, is a pretty heinous violation of the Law of Least Astonishment, and that alone makes it something that should have a spotlight shined on it.
@Indently
@Indently Жыл бұрын
A lot of people don't realise that it's the features of a language that usually lead to bugs, the features themselves are not mistakes, but the way we use them can easily turn into a mistake.
@Indently
@Indently Жыл бұрын
and by a lot of people I mean like 3 people in the comment section 😂
@anshg1104
@anshg1104 Жыл бұрын
I have spent the last few days stuck, debugging my code on why the values in my function would still exist, after calling the function again later on. This all makes so much sense, thanks for the video!!!!
@kruvik
@kruvik Жыл бұрын
Thanks for the explanation, got this warning a couple of times in my code but never understood why.
@5014eric
@5014eric 11 ай бұрын
I made this mistake yesterday. Surprised to find this video today. I was wondering whether missing parameters default to the value you gave it last time. I had to make a small test program to realise what was happening. VSCode, which warns me about a lot of errors, didn't help with with this one.
@daniel_bailo
@daniel_bailo Жыл бұрын
When typehinting a variable that receives None, it's not better "items: list | None = None"?
@Indently
@Indently Жыл бұрын
That's an approach I would admire. Otherwise I guess you should throw an error if it's not an optional. I don't always use optionals because they can really drag out the current line, and if it goes off screen it sucks. But I personally like the approach you provided and would use it whenever I can.
@JusticeNDOU
@JusticeNDOU Жыл бұрын
in the case above just call add_item and have the function return the list you cant declare a list then give it two different names which is effectively what you did there, you did not create two lists you gave the same list declare on the function two names list a and list b
@vpr17
@vpr17 10 ай бұрын
Im a newbie here. How can the function access the same memory location even after its termination? If the list 'items' is a reference to an address, i would assume it looses that address information after function termination. Or does 'items' become a global variable? Or does function call stack work completely differently in python and c++.
@Nerdimo
@Nerdimo 4 ай бұрын
In this example if a user passed an empty list “a” into the function, wouldn’t the returned list be different? It would make sense if you didn’t want to mutate the list passed, but in the case the list is non-empty, it would mutate it. I’d argue you should do if items is not None, not if not items.
@bogdanborta8861
@bogdanborta8861 Жыл бұрын
Good job man, I like your videos so much,they are so useful ❤❤
@HarryC4615
@HarryC4615 Жыл бұрын
Useful video, Thanks
@ricgondo
@ricgondo Жыл бұрын
I shall save this one to my playlist as well!
@Sinke_100
@Sinke_100 Жыл бұрын
This video helped my friend, it is most valued one you made
@OhertRasmus
@OhertRasmus Жыл бұрын
Why did you add `items: list = []` after `if not items:`? Wouldn't it be just fine to do `items = []`? Or is this just a pythonic thing?
@louisdrouard9211
@louisdrouard9211 Жыл бұрын
It is a type hint for his editor, it does nothing else.
@nelmatrix3942
@nelmatrix3942 11 ай бұрын
Actually this feature is very useful. I have made use of this particular feature to implement a recursive algorithm that needs to keep track and update the same list object. It all comes down to your use case of certain feature, and how effectively you use it (that is, if you know what you are doing), therefore I won't consider it a useless feature.
@farisfaikar_r
@farisfaikar_r Жыл бұрын
Are you using Pycharm for this video? If that's the case, how do you make it minimalistic like that? It's so cool
@Kommentierer
@Kommentierer Жыл бұрын
It's the Beta UI like in Fleet
@Randych
@Randych Жыл бұрын
Me at 3:44: "pffffff, what you're gonna do, some guard clause?" Boy...
@bassycounter
@bassycounter Жыл бұрын
i feel like I get smarter when I consume your content, appreciate the stuff
@xzex2609
@xzex2609 Жыл бұрын
It's not stupid mistake if you design it to be , even if you assign it with walrus operator it never be the same list obviously. list_a = add_item('a',list_a :=[]) list_a = add_item('a',list_a :=[]) list_b = add_item('b',list_a ) unless we use it like this it will consider the list_a as a unique list , and the list_b is not a shallow copy of list _a as we may expect it to be
@xzex2609
@xzex2609 Жыл бұрын
it should behave this way , when you make list_a and list_b you just pass the string and the default value was set in your definition of your own function , its not a class that pass an instance (self) to make two different list , you write it to work like this . no interpreter should give you any warning , ... . try even two nameless list , and you will get dofferent id list_a = add_item('a',[]) list_b = add_item('b',[]) the solution is that you pass the list argument that you provide for your function and you yourself gave it a default value , so the interpreter is not giving you any error , cause you , yourself make a single list , if you pass two nameless list when you declaring your list_a and list_b , then every thing just works fine ,
@mehtubbhai9709
@mehtubbhai9709 Жыл бұрын
yes good explanation. The problem arises because the default empty list is created by reference, not by value
@anto_fire8534
@anto_fire8534 Жыл бұрын
why not do something like items = (not items is None and items) or [] instead of a if statement
@Indently
@Indently Жыл бұрын
Because very few people can read that
@anto_fire8534
@anto_fire8534 Жыл бұрын
@@Indently Fair enough however it stops indentation and its not that hard to read if you learn how operators like or and and work in python really
@Red-bg8xg
@Red-bg8xg Жыл бұрын
a more readable way if you want to avoid the and & or operators: items = items if items is not None else []
@Alanpoeta
@Alanpoeta Жыл бұрын
Why isn't the empty list in the if-statement also the same list always?
@allo5668
@allo5668 Жыл бұрын
You create a new list there each time. But the list in the arguments is only created once. Quirk of the python parser
@NoidoDev
@NoidoDev 8 ай бұрын
Just tested if Pylint warns about this, and yes, it does.
@deathdogg0
@deathdogg0 4 ай бұрын
Please don't get me wrong, I love python, but I recently realized the only reason I do now is because I have worked in many statically typed languages. As a result I don't think I would ever make this mistake now. all that is to say though that it just goes to show that not because python is easy to learn and write means beginners should learn it. I actually think python is awful for beginners because of easy mistakes like these. After working with typed languages with optionals, the None solution is obvious, but again only if you come from a statically typed, verbose language. I think learning how memory works behind the scenes and how other more traditional languages work is another great way to avoid this. It would be nice if python added language level type checking, but I guess we can't have it all. Ok back to binging your channel now
@kamurashev
@kamurashev Жыл бұрын
«If not list» is not that good also. Eg empty list is also evaluates for true.
@user-tq9bu6ki2h
@user-tq9bu6ki2h Жыл бұрын
It's better to use "if items is None" instead.
@kamurashev
@kamurashev Жыл бұрын
@@user-tq9bu6ki2h yep, that’s what I meant. Я говорю по русски кстати 😉
@Indently
@Indently Жыл бұрын
I'm sorry guys, this information is wrong, an empty list is a "falsy value" in Python.
@Indently
@Indently Жыл бұрын
@Aleksandar, be aware that you must define the default value of the list to be "None" if you want to do that. And empty list is not the same as "None".
@kamurashev
@kamurashev Жыл бұрын
@@Indently yep, but “not list” for empty list in “if not list” leads to executing the statements in if block as “not list” would be true. This means that if the empty list is passed as a parameter the new empty list would still be created. Basically my point was that this is a bad practice to do if not ‘smth’ if smth is not boolean. It often leads to subtle bugs. So it’s better to check explicitly the thing you’re actually checking for.
@kunalsoni7681
@kunalsoni7681 Жыл бұрын
very smart 🤩
@fafaratze
@fafaratze Жыл бұрын
haha!, its not a mistake nor a bad practice, its just how it works.
@ttrev007
@ttrev007 5 ай бұрын
their is a fine line between a feature and a bug. if it is not working the way you wanted it to it is indeed a mistake.
@JusticeNDOU
@JusticeNDOU Жыл бұрын
this is not a mistake you are just trying very hard to make it a mistake. functions and variables are the same things in python so if a functions returns a list or tuple or so on , there is no need to assign it to another variable as python will never create the same variable twice. so you have to think of functions as if they are not different to variables , you can still just treat function names as variable names they are all the same things.
@Indently
@Indently Жыл бұрын
I promise you I'm not trying hard, this is what a lot of my students send me when they have a problem. I'm very aware it's a feature of Python and it belongs to how Python functions. But every bug is a mistake.
@grayfoxa
@grayfoxa Жыл бұрын
"The biggest stupid mistake" is to use "if" when solving this problem, it is enough to specify "items = items or []"
@Indently
@Indently Жыл бұрын
If you read some of the other comments you might get an idea on why that isn't a working solution.
@grayfoxa
@grayfoxa Жыл бұрын
@@Indently why not? it's perfect works def add_item(item: str, items: list|None = None): items = items or [] items.append(item) print(f"{id(items)=}:", items) return items list_a = add_item('a') list_b = add_item('z', []) add_item('b', list_a) add_item('y', list_b) print(list_a) print(list_b)
@IlariVallivaara
@IlariVallivaara Жыл бұрын
@@grayfoxa : It is similarly broken as the original fix, as it fails when you give it an empty list instance. In this case it does not update that instance but creates a new instance. This makes it behave completely differently with empty and populated input, as demonstrated by this example below: def add_item(item: str, items: list|None = None): print(f"input {id(items)=}: {items}") items = items or [] items.append(item) print(f"output {id(items)=}: {items}") return items list_a = [] list_b = add_item("b", list_a) list_x = ["x", "y"] list_z = add_item("z", list_x) print("list_a:", list_a) print("list_b:", list_b) print("list_x:", list_x) print("list_z:", list_z) ==== This prints out: input id(items)=139785254467776: [] output id(items)=139785254486400: ['b'] input id(items)=139785254453376: ['x', 'y'] output id(items)=139785254453376: ['x', 'y', 'z'] list_a: [] list_b: ['b'] list_x: ['x', 'y', 'z'] list_z: ['x', 'y', 'z']
@gardnmi
@gardnmi Жыл бұрын
I still make the mistake 10 years + of coding with python. The below showcases the concept pretty clearly. def add_item(item, items=[], check_local=False): item_id = f"item_id: {id(item)}" items_id = f"items_id: {id(items)}" items.append(items) if check_local: print("Local Variables") print(locals()['item_id']) print(locals()['items_id']) return item_id, items_id a = add_item('a', check_local=True) b = add_item('b') c = add_item('b', []) print(" Global Variables") print(globals()['a']) print(globals()['b']) print(globals()['c']) Output: Local Variables item_id: 9787744 items_id: 140481494365568 Global Variables ('item_id: 9787744', 'items_id: 140481494365568') ('item_id: 9803104', 'items_id: 140481494365568') ('item_id: 9803104', 'items_id: 140481494401856')
10 Nooby Mistakes Devs Often Make In Python
24:31
Indently
Рет қаралды 54 М.
DEFINITELY NOT HAPPENING ON MY WATCH! 😒
00:12
Laro Benz
Рет қаралды 56 МЛН
LOVE LETTER - POPPY PLAYTIME CHAPTER 3 | GH'S ANIMATION
00:15
Clown takes blame for missing candy 🍬🤣 #shorts
00:49
Yoeslan
Рет қаралды 35 МЛН
5 Good Python Habits
17:35
Indently
Рет қаралды 443 М.
STOP Making These Python Mistakes
19:16
Tech With Tim
Рет қаралды 112 М.
5 Useful F-String Tricks In Python
10:02
Indently
Рет қаралды 280 М.
20 Everyday Tips & Tricks in Python
25:18
Indently
Рет қаралды 17 М.
Modern Python logging
21:32
mCoding
Рет қаралды 163 М.
5 Cool Python One-Liners
12:23
Indently
Рет қаралды 30 М.
Python dataclasses will save you HOURS, also featuring attrs
8:50
12 VS Code Extensions to INCREASE Productivity 2024
27:13
Devression
Рет қаралды 589 М.
Python 101: Learn the 5 Must-Know Concepts
20:00
Tech With Tim
Рет қаралды 1,1 МЛН
Python Hash Sets Explained & Demonstrated - Computerphile
18:39
Computerphile
Рет қаралды 111 М.
DEFINITELY NOT HAPPENING ON MY WATCH! 😒
00:12
Laro Benz
Рет қаралды 56 МЛН