Add THIS To Your Python Scripts! if __name__ == "__main__"
ฝัง
- เผยแพร่เมื่อ 28 ก.ย. 2024
- ⭐ 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...
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.
so can you have several `if __name__ == __main__` clauses that calls different functions in one script?
@@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.
@@MattCantSpeakIt Awesome! Thank you for your response
"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 :)
@@OmegaQuark that is the reason you never get invited to parties bro
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.
Clevon approves of this.
Thanks for the explanation. It helps. Interesting.
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
what is standalone, what is imperative operations, what is top-level script, what is module-only
@@ghhdgjjfjjggj yes
I found this to be the best explanation of the use of __name__. Your illustration is simple and crystal clear.
Many thanks.
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 ]]
Thanks. For the longest time, I saw this command on GitHub and never knew what it meant. Now I do.
Great tutorial... So many junks on TH-cam for this but you explain it very simply.
ty for ur video, i couldnt understand why everyone are using this "nonsense" until now
for more clearity you could have printed __name__ in script1 and and imported it in script2 to see what it prints
woah! what a clear explanation, thank you so much!
amazing..! Thank you for the video!
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
this was the explanation i needed. thank you
Beutifully explained 👏
C L E A N E S T 🔥🔥🔥🔥🔥🔥🔥🔥🔥
i have a dumb question.
why dont just remove " do_something() "
Bro Your the best
Where is the Fire react button on youtube? Only Like would not help in this case, I need a fire react button.
What is your vs code theme
Looks like Synthwave'84, which is what I use.
As a beginner, i am confused fr
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.
Which VS code theme?
synthwave 87' im pretty sure
@@harrydunlop7841 it's '84
try mili theme because It awesome. And made by me 🙂.
But with neon off
WHAT THEME ARE U USING
I watched several videos yet still don't understand. my low iq
Did u understand yet?
I don't get it
bs = "nonsense"
weird = "bogus & non-intuitive"
f"""It's {bs} like this (and many more within) that make Python such a {weird} language"""
"""
The above is an 'f' string & not intended as a multi-line comment,
which uses the same multi quotations mechanic like this
"""
That’s a very useless example
If __name__ == "__mifflin__"
I know, I'm sorry, I couldn't resist. In my defence, I was left unsupervised.
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!
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
Quick, simple and practical. Nice video!
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.
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
hello, what font and theme are u using ?
btw, nice vid, gj
Possibly the most concise and clear explanation of this variable!
This is the simplest and clearest explanation I've come across for this. Thank you!
Very clear explanation. Thank you very much
Short and sweet,thanks
I see , u have been learning python at a great speed.
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
Or you can remove the method call in Script1, import in Script2 and call the do_something() function from there.
# 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.")
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
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
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.
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.
I wish there was a keyword for this. **if "__name__" == "__main__":** is just such an eye-sore.
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.
Now I've undestood why we should use this. Thank you
This is the best explanation I've seen yet. Good job!
So basically we add this clause to avoid duplicate call, right? Makes sense 🎉
finally! an explanation to the use not complicated mechanism!
I was wondering a time ago. Thx u so much for solving my doubt
Nothing like sex music and writing Python script at the same time
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
Can you create a full 10hours Django course. please
This is awesome.. I always wondered what it meant but i was too lazy to look it up. Thanks You
really a very useful video, I got the clarity for the first time about this.
subscribing your channel
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
nice and clear example, failed to put in a context of entrypoint for the execution but thats not a big issue
nice job
What theme do you use for VSCode? It looks so good
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?
I'm confused about this too
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
god, i have finally understood it
Which Font are you using?
thank you!
Hey do you have any course on udemy for python
Thank you so much for the video
Well_paced explanations...
Incredible
Finally. A very simple yet straightforward explanation. Thank you
Why can't you just remove do_something() line from the script1?
I need the name of that theme please
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
Was really wandering what that thing in my StackOverflow'd code does. Thanks.
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
Thanks a lot. Got it now.
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?
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
Thank you man!
gawd I love you
Interesting . . . .
Bro you are awesome
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!!!!!!!!!!!!!!!!!!
nee alutham lae
Finally a good explanation
Great stuff. Treehouse's lesson about this (which their lessons are usually great) was awful.
or you could define a main method and call it afterwards. looks nicer and does the same thing
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
Coming from Java and just started learning python and this was one of the things that I didn’t quite understand
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
Nice fact
It`s very useful and simple knowhow, thank you !
Wow, this video made me finally understand this.
Simple and useful explanation. Thanks. :)
What has confused me is that dot in your function name...is that a good practice?
More semplier than this is impossible to teach and explain. Good video
Thanks, Awesome crystal clear explanation
Thanks for the cool video, you helped me
One million line of code is 1 12th windows code
that is super simple. Really amazing!
Oh boy, amazing explanation
all the 30 min videos and this was the best