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...

ความคิดเห็น • 147

  • @MattCantSpeakIt
    @MattCantSpeakIt ปีที่แล้ว +367

    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 ปีที่แล้ว +1

      @@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 ปีที่แล้ว +1

      @@MattCantSpeakIt Awesome! Thank you for your response

    • @OmegaQuark
      @OmegaQuark 8 หลายเดือนก่อน

      "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 8 หลายเดือนก่อน +8

      @@OmegaQuark that is the reason you never get invited to parties bro

  • @Mr.Not_Sure
    @Mr.Not_Sure ปีที่แล้ว +203

    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 ปีที่แล้ว +1

      Clevon approves of this.

    • @user-zu1ix3yq2w
      @user-zu1ix3yq2w ปีที่แล้ว +9

      Thanks for the explanation. It helps. Interesting.

    • @ghhdgjjfjjggj
      @ghhdgjjfjjggj 3 หลายเดือนก่อน

      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 3 หลายเดือนก่อน

      what is standalone, what is imperative operations, what is top-level script, what is module-only

    • @Mr.Not_Sure
      @Mr.Not_Sure 2 หลายเดือนก่อน

      @@ghhdgjjfjjggj yes

  • @rungsunchoongwattana8370
    @rungsunchoongwattana8370 ปีที่แล้ว +9

    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 ]]

  • @plashplash-fg6hd
    @plashplash-fg6hd ปีที่แล้ว +1

    Thanks. For the longest time, I saw this command on GitHub and never knew what it meant. Now I do.

  • @somnathmanna5285
    @somnathmanna5285 7 หลายเดือนก่อน

    Great tutorial... So many junks on TH-cam for this but you explain it very simply.

  • @AstronomiyiKodlamak
    @AstronomiyiKodlamak ปีที่แล้ว +1

    ty for ur video, i couldnt understand why everyone are using this "nonsense" until now

  • @rishikaushik8307
    @rishikaushik8307 ปีที่แล้ว +1

    for more clearity you could have printed __name__ in script1 and and imported it in script2 to see what it prints

  • @bulelanibotman
    @bulelanibotman ปีที่แล้ว +1

    woah! what a clear explanation, thank you so much!

  • @superben754
    @superben754 7 หลายเดือนก่อน

    amazing..! Thank you for the video!

  • @djangoworldwide7925
    @djangoworldwide7925 8 หลายเดือนก่อน

    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

  • @wh1pper457
    @wh1pper457 11 หลายเดือนก่อน

    this was the explanation i needed. thank you

  • @1_and_only_Crjase
    @1_and_only_Crjase ปีที่แล้ว +1

    Beutifully explained 👏

  • @rryann088
    @rryann088 หลายเดือนก่อน

    C L E A N E S T 🔥🔥🔥🔥🔥🔥🔥🔥🔥

  • @AdvForTimeFrever
    @AdvForTimeFrever 10 หลายเดือนก่อน

    i have a dumb question.
    why dont just remove " do_something() "

  • @saimqazi1663
    @saimqazi1663 ปีที่แล้ว

    Bro Your the best

  • @bidhanry9740
    @bidhanry9740 2 หลายเดือนก่อน

    Where is the Fire react button on youtube? Only Like would not help in this case, I need a fire react button.

  • @avaneeshc
    @avaneeshc ปีที่แล้ว +3

    What is your vs code theme

    • @thepranjalrai
      @thepranjalrai ปีที่แล้ว +1

      Looks like Synthwave'84, which is what I use.

  • @mccauleybacalla2228
    @mccauleybacalla2228 8 หลายเดือนก่อน

    As a beginner, i am confused fr

  • @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.

  • @NikhilPatel-ew6eb
    @NikhilPatel-ew6eb ปีที่แล้ว +27

    Which VS code theme?

    • @harrydunlop7841
      @harrydunlop7841 ปีที่แล้ว +5

      synthwave 87' im pretty sure

    • @thepranjalrai
      @thepranjalrai ปีที่แล้ว +4

      @@harrydunlop7841 it's '84

    • @pixiedev
      @pixiedev ปีที่แล้ว +3

      try mili theme because It awesome. And made by me 🙂.

    • @trimuloinsano
      @trimuloinsano ปีที่แล้ว +1

      But with neon off

  • @yxngboypolo
    @yxngboypolo ปีที่แล้ว

    WHAT THEME ARE U USING

  • @mercantilism954
    @mercantilism954 3 หลายเดือนก่อน

    I watched several videos yet still don't understand. my low iq

    • @anon_faded
      @anon_faded หลายเดือนก่อน

      Did u understand yet?

  • @ksspqf6016
    @ksspqf6016 ปีที่แล้ว

    I don't get it

  • @ellayararwhyaych4711
    @ellayararwhyaych4711 ปีที่แล้ว

    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
    """

  • @fanoflinoa6109
    @fanoflinoa6109 ปีที่แล้ว

    That’s a very useless example

  • @tzisorey
    @tzisorey ปีที่แล้ว

    If __name__ == "__mifflin__"

    • @tzisorey
      @tzisorey ปีที่แล้ว

      I know, I'm sorry, I couldn't resist. In my defence, I was left unsupervised.

  • @SiofraTural
    @SiofraTural ปีที่แล้ว +179

    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 ปีที่แล้ว +25

    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

  • @PracticalCoding.
    @PracticalCoding. ปีที่แล้ว +22

    Quick, simple and practical. Nice video!

  • @heeroyuy298
    @heeroyuy298 ปีที่แล้ว +7

    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.

  • @aufkeinsten7883
    @aufkeinsten7883 ปีที่แล้ว +2

    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

  • @niksonney4462
    @niksonney4462 ปีที่แล้ว +2

    hello, what font and theme are u using ?
    btw, nice vid, gj

  • @nearyou30
    @nearyou30 2 หลายเดือนก่อน +1

    Possibly the most concise and clear explanation of this variable!

  • @humzaashraf321
    @humzaashraf321 ปีที่แล้ว +4

    This is the simplest and clearest explanation I've come across for this. Thank you!

  • @PutXi_Whipped
    @PutXi_Whipped ปีที่แล้ว +5

    Very clear explanation. Thank you very much

  • @erickthamara5154
    @erickthamara5154 28 วันที่ผ่านมา +1

    Short and sweet,thanks

  • @rohankokatanur6426
    @rohankokatanur6426 ปีที่แล้ว +4

    I see , u have been learning python at a great speed.

  • @andrewaldrich3602
    @andrewaldrich3602 ปีที่แล้ว +3

    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

  • @philipberthiaume2314
    @philipberthiaume2314 ปีที่แล้ว +1

    Or you can remove the method call in Script1, import in Script2 and call the do_something() function from there.

  • @Edd211
    @Edd211 8 หลายเดือนก่อน

    # 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.")

  • @Bl0xxy
    @Bl0xxy 7 หลายเดือนก่อน

    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

  • @ajax_og
    @ajax_og 7 หลายเดือนก่อน

    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

  • @scrambledmc3772
    @scrambledmc3772 10 หลายเดือนก่อน

    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.

  • @hugoloopik2154
    @hugoloopik2154 ปีที่แล้ว +4

    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.

  • @HenrikMyrhaug
    @HenrikMyrhaug 9 หลายเดือนก่อน

    I wish there was a keyword for this. **if "__name__" == "__main__":** is just such an eye-sore.

  • @ivanichianus
    @ivanichianus ปีที่แล้ว +7

    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.

  • @rodrigoguimaraes3690
    @rodrigoguimaraes3690 ปีที่แล้ว +2

    Now I've undestood why we should use this. Thank you

  • @dimdongo
    @dimdongo ปีที่แล้ว +2

    This is the best explanation I've seen yet. Good job!

  • @Hephasto
    @Hephasto ปีที่แล้ว +1

    So basically we add this clause to avoid duplicate call, right? Makes sense 🎉

  • @s.hamedstriker5315
    @s.hamedstriker5315 หลายเดือนก่อน

    finally! an explanation to the use not complicated mechanism!

  • @thecarlostheory
    @thecarlostheory ปีที่แล้ว +1

    I was wondering a time ago. Thx u so much for solving my doubt

  • @s.t.6627
    @s.t.6627 ปีที่แล้ว

    Nothing like sex music and writing Python script at the same time

  • @Vitotheking100
    @Vitotheking100 ปีที่แล้ว +1

    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

  • @theblackelephant
    @theblackelephant ปีที่แล้ว

    Can you create a full 10hours Django course. please

  • @all_things_narix
    @all_things_narix ปีที่แล้ว +1

    This is awesome.. I always wondered what it meant but i was too lazy to look it up. Thanks You

  • @waghdipak2358
    @waghdipak2358 ปีที่แล้ว +1

    really a very useful video, I got the clarity for the first time about this.
    subscribing your channel

  • @Caenem_
    @Caenem_ ปีที่แล้ว +6

    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

  • @imdonkeykonga
    @imdonkeykonga ปีที่แล้ว +1

    nice and clear example, failed to put in a context of entrypoint for the execution but thats not a big issue
    nice job

  • @CornFlaekk
    @CornFlaekk 7 หลายเดือนก่อน

    What theme do you use for VSCode? It looks so good

  • @timraiser4811
    @timraiser4811 ปีที่แล้ว +1

    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 ปีที่แล้ว +1

      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

  • @mamadoubah3143
    @mamadoubah3143 8 หลายเดือนก่อน

    god, i have finally understood it

  • @DMZT_dhruv
    @DMZT_dhruv 4 หลายเดือนก่อน

    Which Font are you using?

  • @ironmonkey1990
    @ironmonkey1990 22 ชั่วโมงที่ผ่านมา

    thank you!

  • @vishweshthotakuri6144
    @vishweshthotakuri6144 ปีที่แล้ว

    Hey do you have any course on udemy for python

  • @jovaraszigmantas
    @jovaraszigmantas ปีที่แล้ว +1

    Thank you so much for the video

  • @marcuswest8085
    @marcuswest8085 ปีที่แล้ว

    Well_paced explanations...

  • @ramarisonandry8571
    @ramarisonandry8571 3 วันที่ผ่านมา

    Incredible

  • @lilyempire
    @lilyempire หลายเดือนก่อน

    Finally. A very simple yet straightforward explanation. Thank you

  • @Looki2000
    @Looki2000 ปีที่แล้ว

    Why can't you just remove do_something() line from the script1?

  • @PopsFizzle-wz5jd
    @PopsFizzle-wz5jd ปีที่แล้ว

    I need the name of that theme please

  • @callyral
    @callyral 9 หลายเดือนก่อน

    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

  • @maksiksq
    @maksiksq ปีที่แล้ว

    Was really wandering what that thing in my StackOverflow'd code does. Thanks.

  • @vladthecoldone8804
    @vladthecoldone8804 11 หลายเดือนก่อน

    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

  • @elshanmammadli7731
    @elshanmammadli7731 11 หลายเดือนก่อน

    Thanks a lot. Got it now.

  • @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?

  • @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

  • @eljocacheur
    @eljocacheur ปีที่แล้ว +1

    Thank you man!

  • @gopal.
    @gopal. 6 หลายเดือนก่อน

    gawd I love you

  • @ekanshjaiswal9976
    @ekanshjaiswal9976 7 หลายเดือนก่อน

    Interesting . . . .

  • @ramnivas5252
    @ramnivas5252 9 หลายเดือนก่อน

    Bro you are awesome

  • @anj19911
    @anj19911 10 หลายเดือนก่อน

    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!!!!!!!!!!!!!!!!!!

  • @yuvanraj6226
    @yuvanraj6226 9 หลายเดือนก่อน

    nee alutham lae

  • @oeufleau8543
    @oeufleau8543 ปีที่แล้ว +1

    Finally a good explanation

  • @wesdavis8797
    @wesdavis8797 ปีที่แล้ว

    Great stuff. Treehouse's lesson about this (which their lessons are usually great) was awful.

  • @soggy9648
    @soggy9648 ปีที่แล้ว

    or you could define a main method and call it afterwards. looks nicer and does the same thing

  • @brunoroda3437
    @brunoroda3437 8 หลายเดือนก่อน

    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

  • @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

  • @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

  • @usprpc
    @usprpc ปีที่แล้ว

    Nice fact

  • @JacobTing-ow9sw
    @JacobTing-ow9sw ปีที่แล้ว

    It`s very useful and simple knowhow, thank you !

  • @christiansanchez9880
    @christiansanchez9880 ปีที่แล้ว

    Wow, this video made me finally understand this.

  • @PradipLamsal-s8m
    @PradipLamsal-s8m 10 หลายเดือนก่อน

    Simple and useful explanation. Thanks. :)

  • @ldavader2704
    @ldavader2704 ปีที่แล้ว

    What has confused me is that dot in your function name...is that a good practice?

  • @calcio437
    @calcio437 ปีที่แล้ว

    More semplier than this is impossible to teach and explain. Good video

  • @aryangupta7703
    @aryangupta7703 ปีที่แล้ว

    Thanks, Awesome crystal clear explanation

  • @rosmisha
    @rosmisha ปีที่แล้ว

    Thanks for the cool video, you helped me

  • @ttmso
    @ttmso ปีที่แล้ว

    One million line of code is 1 12th windows code

  • @AMMIN13
    @AMMIN13 8 หลายเดือนก่อน

    that is super simple. Really amazing!

  • @awaisanjum9023
    @awaisanjum9023 ปีที่แล้ว

    Oh boy, amazing explanation

  • @zero_day_xsploit
    @zero_day_xsploit ปีที่แล้ว

    all the 30 min videos and this was the best