Add THIS To Your Python Scripts! if __name__ == "__main__"

  Рет қаралды 169,829

b001

b001

Күн бұрын

⭐ Join my Patreon: / b001io
💬 Discord: / discord
🐦 Follow me on Twitter: / b001io
🔗 More links: linktr.ee/b001io
Background music:
Rain, Book And Cup Of Tea by | e s c p | escp-music.ban...
Music promoted by www.free-stock...
Attribution 4.0 International (CC BY 4.0)
creativecommon...

Пікірлер: 144
@MattCantSpeakIt
@MattCantSpeakIt Жыл бұрын
For people who are confused as to why you'd want to import a script that executes code... You'd usually use this when making a library. You can run your library on it's own to include tests, or just display a help page or something like that when called on its own, which is code you don't want to be executed when you import the library for it's normal use.
@kimfom
@kimfom Жыл бұрын
so can you have several `if __name__ == __main__` clauses that calls different functions in one script?
@MattCantSpeakIt
@MattCantSpeakIt Жыл бұрын
@@kimfom yes, but there is no point in doing so. You'd usually have all of your imports at the top, then all the stuff thats always executed, then you'd have your "if main", in which you'd call anything and everything that you want to be called only if used on it's own. But lets say you have some initialization stuff in the script, and in the middle of initializing, you want to set something differently if the script is called on it's own, then the rest of the init... and then maybe another block of code to be called only as main. // imports // init phase 1 ... if _name_ == '__main__': // change something.. // init phase 2 if _name_ == '__main__': // do something (print?) Thats a bit spaghetti, but yes, that would work.
@kimfom
@kimfom Жыл бұрын
@@MattCantSpeakIt Awesome! Thank you for your response
@OmegaQuark
@OmegaQuark 7 ай бұрын
"it's own" -> its, *its*, ITS, without apostrophe, please. "its" is an adjective, a possessive determiner; "it's" is a shorthand for "it is" or "it has", the third person singular of the verb " to be" or "to have", respectively. It is (it's) really insane the amount of people on the web that write "its" instead of "it's" and vice versa. I suppose it is (it's) a problem that arises from automatic correctors, but it really takes no time to check. Even LLMs now sometimes write the one instead of the other due to the sheer amount of bad examples disseminated through all the web of people that make this mistake. It is (it's) bollocks. I am (I'm) sorry if I point out this fact under you comment. I do not know you, nor did I have the intension to do so. But enough is enough, I have (I've) seen too many wrong examples, and I cannot (can't) take it anymore; I had to comment to free myself of this burden. Please do not take it as a personal attack. Have a good day :)
@roxxel8167
@roxxel8167 7 ай бұрын
@@OmegaQuark that is the reason you never get invited to parties bro
@Mr.Not_Sure
@Mr.Not_Sure Жыл бұрын
This is actually hint to a reader of your code: If your script has *`if **___name___** == '__main__'`* clause, it means: "this script can be imported OR run standalone". If your script doesn't have the clause, then two cases are possible: (a) if it has imperative operations inside, it's standalone-only, top-level script; (b) if there are only functions/classes definitions inside, it's module-only. P.S. And yes, if your script doesn't have the clause AND also mixes imperatives with definitions, it's code smell, IMO.
@stevebot
@stevebot Жыл бұрын
Clevon approves of this.
@user-zu1ix3yq2w
@user-zu1ix3yq2w Жыл бұрын
Thanks for the explanation. It helps. Interesting.
@ghhdgjjfjjggj
@ghhdgjjfjjggj 2 ай бұрын
what is standalone, what is script, what is clause, what is imperative operation, what is top-level script, what is defintion, what is module-only, what
@ghhdgjjfjjggj
@ghhdgjjfjjggj 2 ай бұрын
what is standalone, what is imperative operations, what is top-level script, what is module-only
@Mr.Not_Sure
@Mr.Not_Sure Ай бұрын
@@ghhdgjjfjjggj yes
@SiofraTural
@SiofraTural Жыл бұрын
I love how simple yet straightforward you are with these clips. I actually prefer the video format as opposed to shorts because if I miss a word or can’t understand something right away, I can quickly rewind. The curse of adhd lol. Keep up the awesome work on these Python videos. They’re a lot of help!
@xxmausermanxx8389
@xxmausermanxx8389 Жыл бұрын
Nice. Been learning python now for about 10 weeks. I started seeing this a bunch but with no real reason as to why. Makes so much more sense now
@nearyou30
@nearyou30 Ай бұрын
Possibly the most concise and clear explanation of this variable!
@lilyempire
@lilyempire 12 күн бұрын
Finally. A very simple yet straightforward explanation. Thank you
@ivanichianus
@ivanichianus Жыл бұрын
watched a few other videos of this topic and yours was the most simple to understand, thank you! I wish you had a full Python course video, would love to watch you guide us through from the very basic beginnings to more complex stuff in Python.
@humzaashraf321
@humzaashraf321 Жыл бұрын
This is the simplest and clearest explanation I've come across for this. Thank you!
@PracticalCoding.
@PracticalCoding. Жыл бұрын
Quick, simple and practical. Nice video!
@s.hamedstriker5315
@s.hamedstriker5315 9 күн бұрын
finally! an explanation to the use not complicated mechanism!
@heeroyuy298
@heeroyuy298 Жыл бұрын
Thank you this was helpful. Please make a video about the python import system. I've been a python dev for 5 years and still have no idea how it really works.
@Vitotheking100
@Vitotheking100 Жыл бұрын
Most useful video ever. I have seen so many code with this name==main and didn't get the point of doing it as the code runs perfectly fine without it
@rodrigoguimaraes3690
@rodrigoguimaraes3690 Жыл бұрын
Now I've undestood why we should use this. Thank you
@dimdongo
@dimdongo Жыл бұрын
This is the best explanation I've seen yet. Good job!
@rungsunchoongwattana8370
@rungsunchoongwattana8370 Жыл бұрын
I found this to be the best explanation of the use of __name__. Your illustration is simple and crystal clear. Many thanks.
@svampebob007
@svampebob007 Жыл бұрын
I found it more infuriating as to why you would execute a code on import? I'm a hardware kind of guy. If I wire chip 1 to chip 2 and ask chip 3 to execute what ever chip 2 can do, it will not start by saying: Ah I see chip 2 is connected to chip 1 so we better do what ever chip 1 is doing (unlocks device), chip 2 what do you do? security? 😳, what is my job? INTERFACE?!🤡 I'm pretty comfortable with basic, but anything above that I always get irritated: move A to B "well the developer expected you to do this before that... so you're expectations aren't real so we moved B to Z temporarly moved A to D, Y asked for C so K got B, now A and K are near each other so C can look at Z by looking at L, N always hold B so if you moved N to the left it would overwrite A".... because IF A = B was supposed to be written as IF [[ A = B ]]
@brunoroda3437
@brunoroda3437 7 ай бұрын
When you learning, sometimes you just need little videos to have a whole new understanding of what you're doing :D thank you so much
@hugoloopik2154
@hugoloopik2154 Жыл бұрын
Very good explanation, with good examples that do not only explain what it does and why you should do it, but it also how it works.
@anj_____m
@anj_____m 9 ай бұрын
this is the third video on __name__ that i watched and it was the icing on the cake. i now fully understand what the purpose is, thank you so much!!!!!!!!!!!!!!!!!!
@andrewaldrich3602
@andrewaldrich3602 Жыл бұрын
I saw this in No Starch Press’s python crash course book in the unit tests chapter. I wish they had gone more in depth with it
@Caenem_
@Caenem_ Жыл бұрын
So basically it's to avoid calling functions from an imported module with the line "from xxx import yyy", because we don't want to call them with this lane but later in the main program
@plashplash-fg6hd
@plashplash-fg6hd Жыл бұрын
Thanks. For the longest time, I saw this command on GitHub and never knew what it meant. Now I do.
@somnathmanna5285
@somnathmanna5285 6 ай бұрын
Great tutorial... So many junks on KZfaq for this but you explain it very simply.
@PutXi_Whipped
@PutXi_Whipped Жыл бұрын
Very clear explanation. Thank you very much
@rishikaushik8307
@rishikaushik8307 Жыл бұрын
for more clearity you could have printed __name__ in script1 and and imported it in script2 to see what it prints
@waghdipak2358
@waghdipak2358 Жыл бұрын
really a very useful video, I got the clarity for the first time about this. subscribing your channel
@bulelanibotman
@bulelanibotman Жыл бұрын
woah! what a clear explanation, thank you so much!
@AstronomiyiKodlamak
@AstronomiyiKodlamak Жыл бұрын
ty for ur video, i couldnt understand why everyone are using this "nonsense" until now
@imdonkeykonga
@imdonkeykonga Жыл бұрын
nice and clear example, failed to put in a context of entrypoint for the execution but thats not a big issue nice job
@thecarlostheory
@thecarlostheory Жыл бұрын
I was wondering a time ago. Thx u so much for solving my doubt
@philipberthiaume2314
@philipberthiaume2314 Жыл бұрын
Or you can remove the method call in Script1, import in Script2 and call the do_something() function from there.
@niksonney4462
@niksonney4462 Жыл бұрын
hello, what font and theme are u using ? btw, nice vid, gj
@AMMIN13
@AMMIN13 7 ай бұрын
that is super simple. Really amazing!
@rohankokatanur6426
@rohankokatanur6426 Жыл бұрын
I see , u have been learning python at a great speed.
@all_things_narix
@all_things_narix Жыл бұрын
This is awesome.. I always wondered what it meant but i was too lazy to look it up. Thanks You
@oeufleau8543
@oeufleau8543 Жыл бұрын
Finally a good explanation
@AliAbbas-vp4bm
@AliAbbas-vp4bm Жыл бұрын
Coming from Java and just started learning python and this was one of the things that I didn’t quite understand
@superben754
@superben754 6 ай бұрын
amazing..! Thank you for the video!
@user-ny1rx5ey6w
@user-ny1rx5ey6w 9 ай бұрын
Simple and useful explanation. Thanks. :)
@eljocacheur
@eljocacheur Жыл бұрын
Thank you man!
@aufkeinsten7883
@aufkeinsten7883 Жыл бұрын
Don't have any real experience with python, is there a reason why code from a script runs by default when importing it? Seems weird to me
@ajax_og
@ajax_og 6 ай бұрын
I wish i saw this video LAST NIGHT when I was doing my homework and could not for the life of me figure out how to not get my code to run twice... well you live and you learn lmao
@wh1pper457
@wh1pper457 10 ай бұрын
this was the explanation i needed. thank you
@elshanmammadli7731
@elshanmammadli7731 10 ай бұрын
Thanks a lot. Got it now.
@aryangupta7703
@aryangupta7703 11 ай бұрын
Thanks, Awesome crystal clear explanation
@DaSnipy
@DaSnipy Жыл бұрын
super clear explanation .. thanks man !
@awaisanjum9023
@awaisanjum9023 Жыл бұрын
Oh boy, amazing explanation
@EmailacS
@EmailacS Жыл бұрын
Very helpful,nicely demonstrated ty.
@christiansanchez9880
@christiansanchez9880 Жыл бұрын
Wow, this video made me finally understand this.
@NikhilPatel-ew6eb
@NikhilPatel-ew6eb Жыл бұрын
Which VS code theme?
@harrydunlop7841
@harrydunlop7841 Жыл бұрын
synthwave 87' im pretty sure
@thepranjalrai
@thepranjalrai Жыл бұрын
@@harrydunlop7841 it's '84
@pixiedev
@pixiedev Жыл бұрын
try mili theme because It awesome. And made by me 🙂.
@trimuloinsano
@trimuloinsano Жыл бұрын
But with neon off
@jovaraszigmantas
@jovaraszigmantas Жыл бұрын
Thank you so much for the video
@Kirmo13
@Kirmo13 Жыл бұрын
The explanation of what __name__ is is somewhat vague, but it's 1000% better of the explanation of why you would want to use it
@funnyweirdovideos
@funnyweirdovideos Жыл бұрын
Wow! Thank you so much.
@djangoworldwide7925
@djangoworldwide7925 7 ай бұрын
Why wouldn't you remove the call to do something in script1 instead? Well I guess there are other real life complex situations where this is useful. Thanks it was straightforward
@JacobTing-ow9sw
@JacobTing-ow9sw Жыл бұрын
It`s very useful and simple knowhow, thank you !
@calcio437
@calcio437 Жыл бұрын
More semplier than this is impossible to teach and explain. Good video
@Edd211
@Edd211 7 ай бұрын
# File: example.py def some_function(): print("This function is defined in the module.") if __name__ == "__main__": # This block will only execute if the script is run as the main program print("This script is being run directly.") some_function() else: # This block will execute if the script is imported as a module print("This script is being imported as a module.")
@gopal.
@gopal. 5 ай бұрын
gawd I love you
@CrjaseMechaEngr
@CrjaseMechaEngr Жыл бұрын
Beutifully explained 👏
@rosmisha
@rosmisha Жыл бұрын
Thanks for the cool video, you helped me
@nomadontherun_
@nomadontherun_ Жыл бұрын
Finally! A clear and simple explanation of this....
@maksiksq
@maksiksq Жыл бұрын
Was really wandering what that thing in my StackOverflow'd code does. Thanks.
@mamadoubah3143
@mamadoubah3143 7 ай бұрын
god, i have finally understood it
@ramnivas5252
@ramnivas5252 8 ай бұрын
Bro you are awesome
@Hephasto
@Hephasto Жыл бұрын
So basically we add this clause to avoid duplicate call, right? Makes sense 🎉
@rryann088
@rryann088 Күн бұрын
C L E A N E S T 🔥🔥🔥🔥🔥🔥🔥🔥🔥
@3DimeMedia
@3DimeMedia Жыл бұрын
Very helpful, thank you.
@gabrielm7746
@gabrielm7746 Жыл бұрын
Thanks for the video.
@CornFlaekk
@CornFlaekk 6 ай бұрын
What theme do you use for VSCode? It looks so good
@marcuswest8085
@marcuswest8085 Жыл бұрын
Well_paced explanations...
@soggy9648
@soggy9648 Жыл бұрын
or you could define a main method and call it afterwards. looks nicer and does the same thing
@ksspqf6016
@ksspqf6016 Жыл бұрын
Perfect explanation
@zero_day_xsploit
@zero_day_xsploit Жыл бұрын
all the 30 min videos and this was the best
@mohamedantar6865
@mohamedantar6865 Жыл бұрын
Wow very useful thank you
@callyral
@callyral 8 ай бұрын
ikd python but wouldn't it be easier to add a guard clause before the "main execution" testing if it's NOT "__main__" and exiting if that's the case? so that your code isn't all indented
@theblackelephant
@theblackelephant Жыл бұрын
Sir great content keep it up
@timraiser4811
@timraiser4811 Жыл бұрын
Please help me explain how it doesn't run twice after the if statement is added. He calls the function in script 2 without the conditional so why doesn't it run?
@JhamYT
@JhamYT Жыл бұрын
I'm confused about this too
@thorbjrngrnborg5113
@thorbjrngrnborg5113 Жыл бұрын
Because he is running it from script2, which isn't the "main" (the condition is not met) and therefore it's only being ran from script2 ie. once
@theblackelephant
@theblackelephant Жыл бұрын
Can you create a full 10hours Django course. please
@avaneeshc
@avaneeshc Жыл бұрын
What is your vs code theme
@thepranjalrai
@thepranjalrai Жыл бұрын
Looks like Synthwave'84, which is what I use.
@s.t.6627
@s.t.6627 Жыл бұрын
Nothing like sex music and writing Python script at the same time
@newsgo1876
@newsgo1876 Жыл бұрын
concise!
@AdvForTimeFrever
@AdvForTimeFrever 9 ай бұрын
i have a dumb question. why dont just remove " do_something() "
@ldavader2704
@ldavader2704 Жыл бұрын
What has confused me is that dot in your function name...is that a good practice?
@userpmzjah82
@userpmzjah82 Жыл бұрын
so when you import with the if statement, it doesn't run when importing because __name__ = "script1", but it runs when you call it directly bc __name__ = "main" , right? Does java has the same problem of running twice?
@vishweshthotakuri6144
@vishweshthotakuri6144 Жыл бұрын
Hey do you have any course on udemy for python
@DMZT_dhruv
@DMZT_dhruv 2 ай бұрын
Which Font are you using?
@Looki2000
@Looki2000 Жыл бұрын
Why can't you just remove do_something() line from the script1?
@vladthecoldone8804
@vladthecoldone8804 10 ай бұрын
or you could simply not call the function in the module from which you import? can someone please explain to me why is it needed? I guess I know what it does, syntax and whatnot but simply put, if youre not calling the functions/methods in not main module, why would you even use it when it doesnt run automatically? Edit: okay I see it, useful only when you need to use it as a standalone script for testing so you can have bunch of function calls ready at hand otherwise no need if you aint calling it and why would you even call it or make print statements there since thats whats main module for
@PopsFizzle-wz5jd
@PopsFizzle-wz5jd Жыл бұрын
I need the name of that theme please
@ekanshjaiswal9976
@ekanshjaiswal9976 6 ай бұрын
Interesting . . . .
@saimqazi1663
@saimqazi1663 Жыл бұрын
Bro Your the best
@bidhanry9740
@bidhanry9740 Ай бұрын
Where is the Fire react button on youtube? Only Like would not help in this case, I need a fire react button.
@Bl0xxy
@Bl0xxy 6 ай бұрын
100% i'm not gonna put this in ALL my scripts. i'm going to make sure to only use them in scripts that need to be imported
@scrambledmc3772
@scrambledmc3772 9 ай бұрын
I don't get it. You're calling the function in both files but you only want it to run in one? What's the point of that? When would you ever need this? Point is, any code you want to run in only one file should only be written in that file. This can be applied similarly to variables knowing their own name.
@mccauleybacalla2228
@mccauleybacalla2228 7 ай бұрын
As a beginner, i am confused fr
@mahmudhasan3093
@mahmudhasan3093 Жыл бұрын
Thank you
@yxngboypolo
@yxngboypolo Жыл бұрын
WHAT THEME ARE U USING
@iurymikaelsobraldossantos646
@iurymikaelsobraldossantos646 6 ай бұрын
What theme are you using on vscode?
@KleptomaniacJames
@KleptomaniacJames Жыл бұрын
do this if you want to import this file. if you don't- Who cares! if someone runs code that isn't supposed to run that's on them
@wesdavis8797
@wesdavis8797 Жыл бұрын
Great stuff. Treehouse's lesson about this (which their lessons are usually great) was awful.
@Puzzlers100
@Puzzlers100 Жыл бұрын
The more I learn about python, the stupider it seems. I'm used to Clike syntax and the idea of not having a main function baffles me.
If __name__ == '__main__' for Python Beginners
9:29
Indently
Рет қаралды 18 М.
THIS is Why List Comprehension is SO Efficient!
5:25
b001
Рет қаралды 171 М.
WHO CAN RUN FASTER?
00:23
Zhong
Рет қаралды 45 МЛН
Кадр сыртындағы қызықтар | Келінжан
00:16
If __name__ == "__main__" for Python Developers
8:47
Python Simplified
Рет қаралды 397 М.
The Fastest Way to Loop in Python - An Unfortunate Truth
8:06
mCoding
Рет қаралды 1,4 МЛН
How To Use Recursion In Python
8:50
Taylor's Software
Рет қаралды 7 М.
Python Tutorial: if __name__ == '__main__'
8:43
Corey Schafer
Рет қаралды 2 МЛН
What is Python's Main Function Useful For?
8:08
NeuralNine
Рет қаралды 76 М.
*Args and **Kwargs in Python
3:49
b001
Рет қаралды 268 М.
microsoft doubles down on recording your screen
10:00
Low Level Learning
Рет қаралды 82 М.
Python if __name__ == '__main__' ❓
5:41
Bro Code
Рет қаралды 35 М.
Dijkstra's Hidden Prime Finding Algorithm
15:48
b001
Рет қаралды 162 М.
Как правильно светить смартфоном?
0:18
Люди.Идеи, общественная организация
Рет қаралды 465 М.
Data recovery from MicroSD using PC3000 Flash & Spider Board 😎
1:01
iPhone 15 Plus на Изгибе
0:59
Sergey Delaisy
Рет қаралды 165 М.
Сделал из зарядного устройства нечто!
0:48