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

แชร์
ฝัง
  • เผยแพร่เมื่อ 10 ก.พ. 2025
  • ⭐ 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...

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

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

    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.

    • @Kimo.Codess
      @Kimo.Codess ปีที่แล้ว

      so can you have several `if __name__ == __main__` clauses that calls different functions in one script?

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

      @@Kimo.Codess 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.

    • @Kimo.Codess
      @Kimo.Codess ปีที่แล้ว +1

      @@MattCantSpeakIt Awesome! Thank you for your response

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

      "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

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

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

    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!

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

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

      Clevon approves of this.

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

      Thanks for the explanation. It helps. Interesting.

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

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

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

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

      @@ghhdgjjfjjggj yes

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

    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

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

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

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

    Possibly the most concise and clear explanation of this variable!

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

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

    Quick, simple and practical. Nice video!

  • @erickthamara5154
    @erickthamara5154 5 หลายเดือนก่อน +2

    Short and sweet,thanks

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

    Finally. A very simple yet straightforward explanation. Thank you

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

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

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

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

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

    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

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

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

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

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

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

  • @hugoloopik2154
    @hugoloopik2154 2 ปีที่แล้ว +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.

  • @heeroyuy298
    @heeroyuy298 2 ปีที่แล้ว +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.

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

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

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

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

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

    finally! an explanation to the use not complicated mechanism!

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

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

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

    That was amazing!! New Sub:) I finally understand...I appreciate you!!

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

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

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

    that is super simple. Really amazing!

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

    Very clear explanation. Thank you very much

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

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

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

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

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

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

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

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

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

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

    Finally a good explanation

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

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

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

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

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

    amazing..! Thank you for the video!

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

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

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

    this was the explanation i needed. thank you

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

    Oh boy, amazing explanation

  • @PradipLamsal-s8m
    @PradipLamsal-s8m ปีที่แล้ว

    Simple and useful explanation. Thanks. :)

  • @x5HighDesert
    @x5HighDesert 2 ปีที่แล้ว

    Wow, this video made me finally understand this.

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

    Thank you man!

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

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

  • @ATOMIC_UNIVERSE-SS
    @ATOMIC_UNIVERSE-SS 2 ปีที่แล้ว

    Very helpful,nicely demonstrated ty.

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

    Thanks, Awesome crystal clear explanation

  • @funnyweirdovideos
    @funnyweirdovideos 2 ปีที่แล้ว

    Wow! Thank you so much.

  • @DaSnipy
    @DaSnipy 2 ปีที่แล้ว

    super clear explanation .. thanks man !

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

    Beutifully explained 👏

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

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

    Thanks for the cool video, you helped me

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

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

    Thank you so much for the video

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

    Thanks a lot. Got it now.

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

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

    Finally! A clear and simple explanation of this....

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

    all the 30 min videos and this was the best

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

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

  • @gabrielm7746
    @gabrielm7746 2 ปีที่แล้ว

    Thanks for the video.

  • @3DigitalUK
    @3DigitalUK 2 ปีที่แล้ว

    Very helpful, thank you.

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

    Sir great content keep it up

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

    Perfect explanation

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

    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

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

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

  • @promixinc.8434
    @promixinc.8434 3 หลายเดือนก่อน

    I think main guards are good to implemented in every script.

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

    thank you!

  • @mohamedantar6865
    @mohamedantar6865 2 ปีที่แล้ว

    Wow very useful
    thank you

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

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

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

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

    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

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

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

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

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

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

    Bro you are awesome

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

    My question is how are you getting Python to output under Output and not the Terminal?

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

    Incredible

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

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

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

    god, i have finally understood it

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

    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

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

    Well_paced explanations...

  • @5packsabs
    @5packsabs ปีที่แล้ว

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

  • @newsgo1876
    @newsgo1876 2 ปีที่แล้ว

    concise!

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

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

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

    gawd I love you

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

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

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

    Can you create a full 10hours Django course. please

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

    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.

  • @userpmzjah82
    @userpmzjah82 2 ปีที่แล้ว

    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?

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

    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

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

    Bro Your the best

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

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

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

      I'm confused about this too

    • @thorbjrngrnborg5113
      @thorbjrngrnborg5113 2 ปีที่แล้ว

      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

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

    What is your vs code theme

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

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

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

    Hey do you have any course on udemy for python

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

    ty

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

    Which Font are you using?

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

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

  • @Sous_ss14
    @Sous_ss14 25 วันที่ผ่านมา

    What is the name of the app/website?

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

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

  • @mahmudhasan3093
    @mahmudhasan3093 2 ปีที่แล้ว

    Thank you

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

    I need the name of that theme please

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

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

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

    Which VS code theme?

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

      synthwave 87' im pretty sure

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

      @@harrydunlop7841 it's '84

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

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

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

      But with neon off