You should put this in all your Python scripts | if __name__ == '__main__': ...

Поделиться
HTML-код
  • Опубликовано: 27 сен 2024

Комментарии • 1 тыс.

  • @stevenalexander6262
    @stevenalexander6262 3 года назад +2055

    I've used python for a while now, and I had no clue about the unwritten rules. Thanks for this

    • @mCoding
      @mCoding  3 года назад +128

      Glad it was helpful!

    • @AkosLukacs42
      @AkosLukacs42 3 года назад +20

      What about adding a single line on the top like "you can run this as a script"? Oh, and maybe document commands like arguments, if there are any?

    • @mCoding
      @mCoding  3 года назад +99

      This does exist in the form of "shebang" lines (#!/usr/bin/env python at the top of a script indicates on linux-like systems that this is a script meant to be run by calling /usr/bin/env python script), though these are not portable (particularly to windows) and they do not solve the issue of global variables mentioned in the video. However, combined with the def main if name main idiom, a shebang line can further signal that this is a script and improve clarity for the reader. Documentation is, of course, another great thing to have, though whether your code is documented is a somewhat orthogonal fight to fight :)

    • @s.i.m.c.a
      @s.i.m.c.a 3 года назад +10

      @@mCoding they are portable on windows as "py" extension are linked to py.exe wrapper in default cpython setup, which reading the hashbang and executing the mentioned python version

    • @SirusStarTV
      @SirusStarTV 3 года назад +9

      @@s.i.m.c.a the difference is you can't run python script without .py extension on Windows, because Windows decides which program to pass the path of a script file as first argument by its extension, file association registered once until it's changed by user or a program.

  • @StephenRoseDuo
    @StephenRoseDuo 3 года назад +460

    Reminding me about global variables converted me

    • @mCoding
      @mCoding  3 года назад +59

      Then the video was a success!

    • @thoperSought
      @thoperSought 3 года назад +3

      me too

    • @IqweoR
      @IqweoR 3 года назад +20

      I was using this for years for the same reason. And the reason why I clicked this video - I already forgot why I started using it in the first place. Useful sometimes to just get back to where it all started

    • @VoltageLP
      @VoltageLP 3 года назад +4

      @@IqweoR hahahaha, that's so true

  • @megaing1322
    @megaing1322 3 года назад +1646

    Another reason is that code inside functions actually runs faster (in CPython), since the used Opcodes are `STORE_FAST` and not `STORE_GLOBAL`. That is very noticeable in scripts that do a lot of loops for example.

    • @mCoding
      @mCoding  3 года назад +361

      Interesting point! I hadn't considered that but I suppose it is yet another benefit of avoiding globals.

    • @BRLN1
      @BRLN1 3 года назад +32

      On the other hand if you have time crucial "for"-loops in your main routine ... well I would consider that bad style in itself.

    • @shmubob
      @shmubob 3 года назад +37

      I ran a simple "sum a bunch of numbers in a for loop" the global scope was half the speed of the function scoped run! :o

    • @kircore-fm1740
      @kircore-fm1740 3 года назад +17

      ya smoked some serius cpython sources

    • @leftaroundabout
      @leftaroundabout 3 года назад +23

      @@BRLN1 if you have any time-crucial for-loops being interpreted by CPython then that's _game over_ already right there, never mind function scope vs global scope. Porting the crucial parts to a compiled language (or a library already implemented in another language) will bring _much_ more performance improvement than anything inside CPython. In some cases the (JIT-) compiled language can be Numba, which is easy to do from Python.

  • @zacbailey6112
    @zacbailey6112 2 года назад +45

    this stuff is great for someone who has learnt to code at uni, but you just get chucked in the deep end. see stuff like this everywhere but don't know what it means. great explanation

    • @mCoding
      @mCoding  2 года назад +7

      Thanks for the kind words!

  • @rubenduarte1468
    @rubenduarte1468 3 года назад +665

    As someone just starting to learn Python, this gave me a headache :)
    I have so much to learn...

    • @abdullahnadeem1823
      @abdullahnadeem1823 3 года назад +20

      Don't worry, you'll make it. Although, im nothing special myself

    • @pdc250
      @pdc250 3 года назад +38

      It's fun once you start in a bigger project. I did one for college and learnt alot as I went along it. You also learn things not to do in the future. Enjoy the journey!!

    • @tunailker8
      @tunailker8 3 года назад +29

      Don't worry, as long as you believe in yourself, nothing can stop you!

    • @nebster333
      @nebster333 2 года назад +2

      this is me :D let's not give up!

    • @chrishofer6370
      @chrishofer6370 2 года назад +1

      Same...

  • @aleksanderkrauze9304
    @aleksanderkrauze9304 3 года назад +410

    This flashing "captions" are VERY funny. Keep 'em coming!

    • @mCoding
      @mCoding  3 года назад +67

      Thanks! I wasn't sure if people would like them or find them annoying! Anyone reading please do let me know!

    • @joseflat
      @joseflat 3 года назад +31

      @@mCoding I would probably consider making them smaller, and perhaps near the botton edge of screen. Many people here (including me) are happy with youu because of the straightforward profesional style, and this, in my opinion, slightly ruins it.

    • @Proprogrammer001
      @Proprogrammer001 3 года назад +9

      @@mCoding Those kept video very entertaining. I've been using this idiom forever and know the reasons but still watched to the end and I think this was why. The flashback to learning java actually made me laugh out loud.

    • @tobb10001
      @tobb10001 3 года назад +7

      @@mCoding I love them.
      But I think people who come here via search might consider them inappropriate, especially when the rest of the screen turns darker for a moment and the code is difficult to read due to the change of brightness.
      I would prefer them to be away from the viewers focus and not effect the rest of the view, so those who are interested can read it but anyone else can ignore it, which is not possible at the moment.

    • @Kenny_G_Loggins
      @Kenny_G_Loggins 3 года назад +7

      @@mCoding I can see what other people are saying but I like it. If you are going to change it by moving it to the side/bottom, Please leave it up for 1 second longer. I watch all your videos for the content and those blurbs are just a bonus so I'll be here either way. Maybe do a video on some more unwritten rules.

  • @dwarakanandan
    @dwarakanandan 3 года назад +46

    At first i was like this dude wants to flex with fancy looking code, then came global variables in a pickle file. Consider me converted 🙏

    • @PixelThorn
      @PixelThorn 2 года назад

      Flexing programmers aren't really programmers in my opinion.

  • @susu5331
    @susu5331 3 года назад +165

    Thanks, I’ve been writing Python for quite a while and it never came across to me that leaving those variables global is a potential source of bugs. Now I’ll definitely put all those stuffs inside the main function!

  • @Shynaku
    @Shynaku Год назад +24

    Another reason to use a main function is it makes it easy to turn a script into a library. At one point, I made a script with a custom class. Then, in another script, I realized that class would be really useful. Since the first one had a main function, I could simply import that class from the first script.

  • @ianrickey208
    @ianrickey208 3 года назад +27

    I really appreciate your vids and that you go the extra mile of example and explanation. 99% of tutorials show a cursory overview of some new shiny library or module, scattering global variable spaghetti to the four corners of your code base. In these days of stackoverflow copy pasta, your vids remind us that frequently more elegant and reliable implementations are not always 200% more effort.

    • @mCoding
      @mCoding  3 года назад +7

      Thanks for noticing! It is hard to convey these subtle issues to a large audience but I'm very happy to see people like you getting the point!

  • @zTJq40sl
    @zTJq40sl 3 года назад +61

    Another reason to do this is so you can order functions and functionality (except for the trivial and idiomatic if-name-main-main block) top-down, and thus roughly in the order they will call each other, which makes the code much easier to comprehend and understand.

  • @jjbankert
    @jjbankert 3 года назад +46

    I do the same, but had a different motivation. I like it when I read a file top to bottom that the written order somewhat resembles the execution order. So a main function with high level function calls that describe the entire script will be the first thing you read.

    • @foodice11
      @foodice11 3 года назад +8

      In many languages the opposite is mandatory, requiring as the file is read top to bottom in one pass. In this case all calls must come after their definitions.

    • @15Redstones
      @15Redstones 3 года назад +12

      @@foodice11 and with the main() call at the very bottom that's no problem

    • @DrDeuteron
      @DrDeuteron 2 месяца назад

      no, the 1st thing you read is the docstring.

  • @1234admir
    @1234admir 3 года назад +168

    Python programmers: "Other languages are so constraining, forcing you to go through tedious steps to run something."
    Also python programmers: "We need to have these constrains so our code is easier to understand and to avoid errors."

    • @silak33
      @silak33 2 года назад +4

      Constraints can be fine if you need to write something of a size which needs it / something more permanent but can be a pain if you just want to test something.
      I primarely write c# and find it super annoying to do all the steps I have to do just to test out a new language feature or maybe a library I haven't used before. Just opening a file and writing a short "script" to test it sounds like a dream (even if it had to compile)

    • @_xylotus_
      @_xylotus_ 2 года назад +5

      C Programmers: "We have to write code mem safe so we don't get any leaks!"
      Python Programmers: "Garabge Collection"
      every language has it's positive and negative perks, that's what makes them more individual I guess.

    • @aba22125
      @aba22125 2 года назад +8

      While Python can be written without any classes and functions, it's not recommended for big scale projects. And once you learn classes and functions, it's kinda ez and super neat. I can comeback to code months later, fully understanding it, as opposed to my noobier days, when I had to rewrite code cuz I didn't understand how to work with it after a week

    • @_xylotus_
      @_xylotus_ 2 года назад

      @@aba22125 agreed

    • @plrc4593
      @plrc4593 2 года назад +1

      @@aba22125 You didn't understand it, becasue you didn't use classes/functions?

  • @spacehooliganzack7429
    @spacehooliganzack7429 3 года назад +7

    Wow, I've been trying to figure that out for so long, and literally nobody I talked to could explain it. Thank you so much for finally clearing up the confusion

  • @mensaswede4028
    @mensaswede4028 2 года назад +384

    Yes, there’s a reason why the “higher learning-curve languages” like Java or C++ have a bigger learning curve than Python. It’s not because the people who designed Java were too dumb to create a language with a small learning curve, but rather because the additional structure of these higher-learning-curve languages is actually useful. We can manually add the additional structure of these more advanced languages to Python to gain the structural advantages, but then Python loses the advantage of being a easy-learn beginner language.

    • @Madthrax23
      @Madthrax23 2 года назад +19

      But in this case, is it really easy to learn ? If you can't understand underlying concepts ? As a java dev I can't understand what python does with type, structures, etc.. This video is a good example...

    • @NotoriousPyro
      @NotoriousPyro 2 года назад +6

      Being easy to learn and having additional structural advantages are not mutually exclusive, there are many "structural advantages" already that can be enabled e.g. 'typing' module and other modules which add certainly more complexity, but also structure. But python is becoming easier...
      You don't need to be complex to have features.

    • @volbla
      @volbla 2 года назад +46

      A less steep learning curve does not mean a lower utility ceiling. The advantage of python isn't that these confusing structures are useless and you'll never need them. It's that _you don't have to start off with them._ It lets you approach programming at a gentler pace, gradually working up to more complicated ideas.
      That's what learning curve means. The difficulty of each step in the learning process. It doesn't mean there are no complicated things to learn, nor that there's a limit to what the tool can do if you master it.

    • @oksatoki
      @oksatoki 2 года назад +16

      @@volbla yep, python learning curve is higher than any other programming language, but people mostly missunderstand what learning curve is. Python starts off being so easy, but as you go deep it can go as complex as any other language, for example in java from the start you will need to do what here is exaplain with the 'public static void main(...){...}' in order to just print something in the console, hence the learning curve is not that pronounced

    • @GrantGryczan
      @GrantGryczan 2 года назад

      @@oksatoki you mean lower?

  • @re.liable
    @re.liable 3 года назад +17

    I think I will never not feel horrible(?) whenever I use a dedicated `main` function, even if I understood all of the points you've given. Gotta get over this mindset

    • @mCoding
      @mCoding  3 года назад +25

      The feeling goes away fast if you ever waste an hour due to one of the issues!

    • @farris8503
      @farris8503 3 года назад +7

      Interesting, why do you feel that way? For me it's the opposite, going from C to Python it felt really awkward not having a main function.

    • @re.liable
      @re.liable 3 года назад

      @@farris8503 I have it stuck on my head that entrypoint functions are C and Java things. Python doesn't need that. Whenever I see `main` functions, my brain immediately thinks that the code is "smelly" because there's no "need" for that. It "feels" like a "mistake" a beginner would make, who is trying to switch from a C-based language into Python. And it sucks because I know better than that and I'm trying hard to get over it now...

    • @ITech2005
      @ITech2005 3 года назад +1

      @@farris8503 Same here from Java

  • @esmith2k2
    @esmith2k2 3 года назад +7

    im a very new programmer starting a CS degree, my first programming class, once we learned what functions were, this was the first thing he taught us. Ive used it ever since

  • @quamrana
    @quamrana 3 года назад +24

    Great tip about "name main" in PyCharm. I'm going to use that for every script from now on!

  • @NewspireMakes
    @NewspireMakes 3 года назад +48

    This can even be useful for non-scripts as well. I often include a main in library modules that include an example or even test the module. That way an unfamiliar user can can run the file and see how the module behaves and how it to use it.

    • @wallacevieira8853
      @wallacevieira8853 3 года назад +11

      I was about to write the same. Keeping a "__name__ == '__main__'" as an example of how to properly use my libs has saved many hours of work from my coworkers.

    • @Pokornz
      @Pokornz 2 года назад

      This ^^

    • @djciregethigher
      @djciregethigher 2 года назад +2

      @@wallacevieira8853 can you elaborate with an example?

    • @dko1905
      @dko1905 2 года назад

      Wouldn't it just be easier to write an example in the library documentation?

    • @Davide73
      @Davide73 2 года назад

      @@wallacevieira8853 bad practice... So if your coworkers forget to remove your "example", they will deploy in production a library with an example embedded... I understand every day more with Python is chosen at my kid school to introduce them to coding...

  • @FloatingSunfish
    @FloatingSunfish 2 года назад +62

    I've actually been using a dedicated "main" function for a while now.
    It just seemed natural to *_not_* put your main code inside an if statement.

  • @EnternodeCS
    @EnternodeCS 3 года назад +16

    One of the things that's always bugs me is the fact that some of Python's best practices, like this one, are so... hideous. It's soured me to the language as a whole.

    • @EnternodeCS
      @EnternodeCS 3 года назад +1

      *always bugged me

    • @alexjusto9591
      @alexjusto9591 3 года назад +2

      What's wrong with defining a function and calling it like this?

    • @EnternodeCS
      @EnternodeCS 3 года назад +8

      @@alexjusto9591 nothing, it's just visually repulsive in comparison to the rest of the language's simplistic beauty

    • @Elthorr149
      @Elthorr149 2 года назад

      After a while you'll get more confused if you don't see the if statement than the opposite. It will look for you as a button designed this way

  • @TheDarkOne629
    @TheDarkOne629 2 года назад +4

    Good video.
    I tutor C and found that students find it more intuitive when there's only one main in the project.
    Lately, I had to explain to someone why, in functional languages (lisp in this case) you don't put "impure" behaviour (or any behaviour) at the top-scope of a given module/namescape. He had a web-request there. He found it much nicer to put everything into the top-scope because Haskell's syntax for main is so ugly.
    TLDR: I think that enforcing a single point of entry is easier to understand and that just-in-time execution is king (which is besides the point).
    Have a nice day. :)

  • @chiefmofo
    @chiefmofo Год назад +8

    I work in PyCharm and artist software like Maya simultaneously when I write art tools. Including this helps steamline testing considerably! I will sometimes start roughing things out in Maya's console and then refactor my work in a separate IDE like PyCharm or Rider as a standalone script. I can then continue work in a coding environment but still be able to quickly test in context.

  • @danielmajer1648
    @danielmajer1648 2 года назад +2

    Been already 5 months that I started learnint Bioinformatics (i was working a cook for 10 years) and feeling my head wants to blow up, but this realm is amazing! Sooooo much to learn and when finally you start to catch on a new stuff, the feeling is even better than a 200 cover dinner rush!

  • @bendirval3612
    @bendirval3612 2 года назад +22

    Depends on the types of projects you do. If you only ever write short scripts that are a single file of a few dozen or hundred lines and are never loaded by other scripts, then the benefits of this idiom are greatly reduced and the costs remain. In general, structure scales well but imposes costs on little projects.

    • @dinosoup
      @dinosoup 9 месяцев назад

      As a security engineer, I'm meant to keep things as light as possible since I'm running my scripts 100s of times a day against 200k machines at my company. I'm the backup, I'm the "additional libraries", nobody else maintains/uses my stuff. There's no way I could get away with this, it would just be wasteful additional processing.

    • @Zekromaster
      @Zekromaster 9 месяцев назад +1

      It's a single "if" and a function indirection. There's no usecase where you're at the same time using python AND avoiding a single function call is an actual valid performance concern.

  • @hossumquat
    @hossumquat 3 года назад +124

    I am learning python and saw this in various places but didn't know what it did or why I should use it. Now I finally understand the reasoning behind it and why it should be used. Seems like this is something that should be explained by anyone who is going to teach python to others.

  • @tributontenkaiiceblast2646
    @tributontenkaiiceblast2646 2 года назад +1

    I've been doing Python on the side for personal projects and never even learned this in a college class about the language. Thanks for the info!

    • @mCoding
      @mCoding  2 года назад

      You're very welcome!

  • @OshalevshiyKeks
    @OshalevshiyKeks 3 года назад +18

    Another reason to use "if name == main":
    When you use "if name == main", all your code is wrapped in a function, so all variables are local. Programs that use local variables are faster than those that don't. Therefore, the script with "if name == main" could run several times faster

    • @JJSogaard
      @JJSogaard 3 года назад +1

      Didn’t know that. Thanks!

    • @Acid31337
      @Acid31337 2 года назад

      Thats always kills me, when someone tries to squeeze another tiny bit of performace out of python, slowest language ever.
      If your python program need that, you did something wrong at the point when you chose python for your task.

    • @pawemarsza9515
      @pawemarsza9515 Год назад

      if statement doesn't define a function, lol
      You've gotta learn what a code block and functions are. You could do something like:
      def main():
      # do stuff
      main()
      without "if name == main" at all.

    • @OshalevshiyKeks
      @OshalevshiyKeks Год назад

      @@pawemarsza9515 ofc you're right, but it a little forces you to use main() function.
      And I think that your "you've gotta learn" phrase sounds offensive =)))

  • @aba22125
    @aba22125 2 года назад +1

    Crazy how back a year or two I thought I'll never learn this crap. But now I fully understand it. And I usually just write libraries with classes and functions instead of just a script, so I'm good.

  • @lepsycho3691
    @lepsycho3691 3 года назад +14

    Make the code clearer and easier to debug. I specifically love it when I write a more complex program with different classes in multi file project. It allows me to test different modules and have different behavior when called as a script or as a module if I want.
    Thanks for the great explanation, I think this is going to help a lot of people!

    • @Acid31337
      @Acid31337 2 года назад +1

      Unnecessary complexity is all fun and games, until you actually need to do your job, you get paid for.

    • @aba22125
      @aba22125 2 года назад

      @@Acid31337 It's not unnecessary complexity lmao, you simply don't understand it and fear it. While in reality this is easy stuff and it helps you.

    • @Acid31337
      @Acid31337 2 года назад

      @@satunnainenkatselija4478 but thats exacly what everyone does.
      Why otherwise you think every typical java/c++ "OOP-best-practices" project end up in pile of managers, services, factories and DAO? That takes 1 week and 1000 SLOC to add 1 field to API...
      We've lived for 2+ decades when "best practice" is to prematurely complicate software and called it "clean architecture", not forget call everything else "spaghetti". Now we're slowly trying to throw that toxic idea away and return to normal programming

  • @dwagonyt
    @dwagonyt 2 года назад

    I like how the thumbnail answered the title and was self explanatory but yet we still clicked on this video.

    • @mCoding
      @mCoding  2 года назад +1

      Presumably you want to know *why* you should do this and hear the reasons rather than blindly following advice from the internet. 🙃

  • @atrus3823
    @atrus3823 3 года назад +5

    One other benefit of using a main function is that it makes your script play nicely with other tools, e.g., setuptools' console_scripts. I'd even go further and say that main() should have no parameters and should only contain stdin and CLI arg handling/parsing/validation code (maybe file handling too). Business logic should either be in an external library, or for single-file scripts, there should be another function that acts as the entry-point for business logic. This way, the script can be used as a library.

  • @jsancarl
    @jsancarl 2 года назад +2

    My reason why i started using this is to be able to define functions on lines below where they are used

  • @sicus0
    @sicus0 3 года назад +41

    The shebang is also a must in (Python) scripts.

    • @12345origamimaster
      @12345origamimaster 3 года назад +5

      Even if you are on windows ;)

    • @bersK00
      @bersK00 3 года назад

      Was it about setting the proper python version ( v3 vs v2? ) or just being able to run it directly as a script without the python prefix.

    • @sicus0
      @sicus0 3 года назад +3

      @@bersK00 To run it directly on the correct version "#!/usr/bin/env python2" or "/usr/bin/env python3" (or old style #!/usr/bin/pythonX"). With the prefix (python2 script.py), the shebang is not used.

  • @Pope_
    @Pope_ 2 года назад +2

    as someone who dosent know how to use python or any programming language and isnt learning, your videos are entertaining and informative as to how python and other languages work at a simple level.
    Update a year later: I just started my computer science degree :)

  • @ironbard4901
    @ironbard4901 3 года назад +11

    Neat! This beautifully explained some quesstions, that I didn't even know how to ask, from when I first learned Python.
    Every now and then I'd get unexpected errors or bugs that I couldn't for the life of me deconstruct - and now I finally know!
    I'm looking forward to your future content and diving into your older stuff.
    Thank you!
    - Sincerely, a new subscriber.

    • @mCoding
      @mCoding  3 года назад +3

      Great to have you watching!

  • @ADEpoch
    @ADEpoch 7 месяцев назад +1

    The multiprocessing reason is the reason why this has become my standard over the years. Took me ages to figure out what was wrong first time I stuffed it up!

  • @22beanbean
    @22beanbean 2 года назад

    I learned Python from a very knowledgeable friend. He taught me best practices. At first i ignored all best practices and just wanted to code. After a while i started implementing def and class is my code and while I started adding if name.

  • @AnweshGangula
    @AnweshGangula 3 года назад +11

    Additional advantage of this is you can organize the functions in any order.

  • @kiritoasuna8602
    @kiritoasuna8602 3 года назад +2

    Wow, this is quality content. This channel is going big, mark my word.

  • @Vousie
    @Vousie 3 года назад +21

    Eh... In larger python programs where you have multiple files, sure this could be useful. But I'm certainly not gonna put it "in all [my] Python scripts". Any single-file scripts can easily remain as they are and it keeps them simple.

    • @aloysiuskurnia7643
      @aloysiuskurnia7643 3 года назад +8

      Yeah, I do it in my more serious projects. For sketches I usually just blindly write anything just the way it is

    • @Davide73
      @Davide73 2 года назад

      Is this a joke? In a "larger python programs" you are having this approach??

  • @always-ask-why
    @always-ask-why 6 месяцев назад

    This is the best and most complete explanation I've seen on this question.

  • @bobchannell3553
    @bobchannell3553 3 года назад +3

    There's a very good Corey Schafer video from 2015 that explains this very well. It doesn't talk about the global variables though.

  • @The1RandomFool
    @The1RandomFool 2 года назад +2

    The first reason I learned about creating the main if statement and the main function was actually for multiprocessing. I use Python for my mathematics hobby with the SymPy module or with SageMath and wanted to utilize all the threads of my CPU.

  • @FirstLast-kv1iq
    @FirstLast-kv1iq 3 года назад +9

    non discord but youtube notification gang

  • @leogama3422
    @leogama3422 2 года назад +1

    The multiprocessing fork bomb really surprised me!

  • @robertolin4568
    @robertolin4568 2 года назад +6

    I like how straight-forward Python is, but conventions like this, along with tragic package management are really against the Zen of Python.

  • @liveactionsteve
    @liveactionsteve Год назад

    I like that I can put the main() function at the top of the script and define the functions that it calls lower down, without worrying about calling a function before it is defined.

  • @TheMrRuttazzo
    @TheMrRuttazzo 2 года назад +1

    I've been learning Python for quite some time now, and I've always wondered when I was browsing for code examples etc. why people were doing that basic-looking extra-hoop to jump through in their scripts.
    Now I know... And knowing is half the battle! *PY JOOOE*

    • @Davide73
      @Davide73 2 года назад

      They were doing that because it is spaghetti-style code

  • @davidyu1813
    @davidyu1813 3 года назад +6

    I put this in my vimrc so that I don't have to do it manually again and again lol it's a good practice indeed

  • @Xvladin
    @Xvladin Год назад

    I've been doing this for years but I never knew why. I just knew thats what youre supposed to do lol.
    Thanks!

  • @bobchannell3553
    @bobchannell3553 3 года назад +7

    Of course there's a reason to do it. We want to make Python as complicated as Java or C++.

    • @mCoding
      @mCoding  3 года назад +6

      Ahh yes, the language flex argument.

    • @chri-k
      @chri-k 3 года назад +5

      C still wins on the monstrosity potential;
      int B(void*X){return*(int*)&X;};int(*F(void*A,void*(*F)(void*)))(void*){int(*X)(void*)=&B;X(F(A));return X;}

    • @rjthescholar177
      @rjthescholar177 3 года назад

      @@chri-k Can do in C++ too...

  • @wojciechwilimowski985
    @wojciechwilimowski985 3 года назад

    I'm a .NET dev, but now I know why I do the thing I saw everyone do in pro Python code. Thanks!

  • @nottheengineer4957
    @nottheengineer4957 2 года назад +4

    Thanks for explaining this. I only use python for university stuff, so to me this is just a way to signal my professor that I know what I'm doing (which may or may not actually be the case).
    I like that the style of explaining with minimum viable examples, it leaves room for discussion and that room is used, as you can see from the other great comments.
    Usually, I don't care too much about python, but this was a great video. Keep it up and consider me a subscriber!

    • @mCoding
      @mCoding  2 года назад +2

      Great to hear! I also totally agree, my comments contain many gems and great suggestions from other experienced Python programmers! Awesome audience and glad you're part of it!

  • @zacharygibbs2355
    @zacharygibbs2355 7 месяцев назад

    While developing, I like to write the code directly in the if block, mainly so that if I run the file in interactive mode, the variables are there for me to inspect and modify to write the next lines. Not something you can do in a main() function without breakpoints.

  • @BlackHermit
    @BlackHermit 3 года назад +5

    I already use this all the time! :)

  • @Khyrid
    @Khyrid 3 года назад

    You put the comma after Hello, that blew my mind.

  • @fosspointer
    @fosspointer 3 года назад +3

    watching this as a c++ programmer who's never worked with python before

  • @LE-bo4pp
    @LE-bo4pp 2 года назад

    I am brand new to coding. I am very confused but I will keep watching.

  • @Luclecool123
    @Luclecool123 3 года назад +3

    Just so you know f"__name__={__name__}" can be written like f"{__name__=}"

    • @DanTheManTerritorial
      @DanTheManTerritorial 3 года назад

      He knows it, I saw him doing it in one of his videos. I guess he wanted a ":" here, not "="
      Edit: although I don't see any reasons for that tbh

  • @samj1512
    @samj1512 2 года назад +2

    Definitely a good vid! When I asked my teacher their answer was basically "it's better lmao"

  • @nathanwise9271
    @nathanwise9271 3 года назад +4

    Your videos are always great

    • @mCoding
      @mCoding  3 года назад +2

      I appreciate that! Thanks for watching!

  • @SoulExpension
    @SoulExpension Год назад

    I grew up with Borland: init(); run(); done(); so it makes sense to me. You could create your own idiom, or "top-level super structure", for loading code. It is the precept to OOP, prior to object definition. Borland and Microsoft considered it critical for GUI app development, large code base, and object class structure.

  • @ray30k
    @ray30k 3 года назад

    I've had scripts break hard, until I did the \_\_name\_\_ == "\_\_main\_\_" thing. It's pretty important that you do it, for sure!

  • @TigerWalts
    @TigerWalts 3 года назад +4

    I use this in files that have functionality that I want to be able to either import into another script or run from the command line. The main function parses the command arguments and then instantiates classes and runs functions based on those arguments.

    • @BlkRider
      @BlkRider 3 года назад

      yeah, you definitely should NOT do that. Just move the functions you'd like to reuse to a separate module to keep your code clean and readable.

    • @TigerWalts
      @TigerWalts 3 года назад +2

      @@BlkRider I both agree and disagree to this point. It really comes down to the scope of responsibilities of the code in the file.
      If the scope is narrow and I can write a very short main function to invoke it from the command line, then I can only see this as a bonus. Anyone looking at the code can now see a working example of how to use the code in the file (in addition to doc strings).
      If I find that I am rewriting/reusing classes/code from that file that isn't part of the main responsibility. That's when I refactor it into its own file.

  • @Kasslim11
    @Kasslim11 9 месяцев назад

    I've found a main function is also useful when making a tool that can either be used as a library in other projects or executed directly to perform a specific task in isolation. E.g. "convert the given binary file to a .csv" when executed vs only having a convert function when imported

  • @senhalil
    @senhalil 3 года назад +8

    I'll be honest not having "you" at the corner let me focus on the subject a lot better.

    • @mCoding
      @mCoding  3 года назад +4

      😳

    • @parkerkeller9778
      @parkerkeller9778 3 года назад +1

      @@mCoding fwiw i like it! This way is fine too, but something about having a video feed makes it feel more like a class which i like

    • @kaskilelr3
      @kaskilelr3 3 года назад +1

      @@mCoding nah keep the facecam, you have an awesome face

    • @thepurplesmurf
      @thepurplesmurf 3 года назад +5

      It's psychological. With the face on the screen you unconsciously try to make eye contact with that person (although only a video) to suggest that you pay attention. This is why you take your eyes off the screen/code numerous times during the lesson which can distract your brain. Without that other "person" you have nowhere else to look other than the code and you stay more focused.

  • @TheOnlyEpsilonAlpha
    @TheOnlyEpsilonAlpha 9 месяцев назад

    I use it mainly for testing purposes. If you run a module as a script, you always get the test function

  • @GyroCannon
    @GyroCannon 2 года назад

    Not a Python guy at or outside of work, but I've seen this enough to be curious about it
    Good to know for the future if I ever dive into Python again!

  • @ipb4isleep
    @ipb4isleep 3 года назад +5

    I didn't know dunder == double underscore

  • @POINTS2
    @POINTS2 3 года назад +2

    I have been accused as well. Thanks for the validation!

  • @mediocreman6323
    @mediocreman6323 Год назад

    I don't use it for a “throw-away”-script. For instance, I once renamed a bunch of files in a way in which a python-script was the most practical (mmv and consorts just didn't cut it), but I knew I would never do this again, and if, I would write a new script. So, if I do not use “main”, it means: _I am a glorified one-liner, do not use me again!_

  • @hugoavila5049
    @hugoavila5049 7 месяцев назад

    Damn im so glad i was patient enough to wait to come across your video… thank you appreciate the wisdom🙏

  • @pranavnigam11
    @pranavnigam11 3 года назад

    the reason at the end convinced me to use the def main part too

  • @hung-tienhuang3640
    @hung-tienhuang3640 3 года назад +4

    Just love cpp so much that I try to make all my python code like cpp
    Things are not only put in main, but also almost all the var are annotated with type hint

    • @wsrgs4
      @wsrgs4 3 года назад

      imo a good text editor/ide should be able to tell you the types without you needing to explicitly annotate them, and you don't really care about what the type is for local variables anyway. type annotations for functions, on the other hand, are great for documenting the contract.
      and cpp also supports type inference (auto keyword).

    • @gamekiller0123
      @gamekiller0123 3 года назад

      @@wsrgs4 You do care about the types of local variables. Autocompletion works a lot worse when you don't know the type (though in python you can't even know for sure even with the type). Often you can infer the type from the usage of the variable, but if you use a library without type hints you're out of luck.

    • @wsrgs4
      @wsrgs4 3 года назад

      @@gamekiller0123 good point about libraries without annotations. but in the case where all functions *are* typed, your editor should be able to infer the type of local variables and provide the correct autocompletions, I would think. I guess I shouldn't have said that one doesn't care about the type, but rather that it doesn't usually need to be explicitly written.

  • @JelMain
    @JelMain 9 месяцев назад

    Amusingly, main() was imported by Bell Labs when they wrote the B Compiler, as they did what was commonplace in those days, borrow good ideas. That one was a poor joke of mine, when my class teacher, who'd won the New Scientist Competition of the year, was stymied by IBM, who'd commandeered START() and BEGIN() as file-handling routines in BASIC 1: he'd intended to use one as his start function in a compiler he'd written. Many years later, I had to touch base with Bjorn Sjostrup in some banking coding for options, and he confirmed, they had borrowed it. The joke? I suggested teach use my surname, he looked sideways, muttered it's not such a bad idea at that, and that was that.

  • @KangJangkrik
    @KangJangkrik 3 года назад +14

    I dunno man, I always treat python like script (replacement of bash and batch), so that thing isn't so useful
    Also it is a good practice for library to put all logic inside functions, running it directly won't do anything

  • @deemon710
    @deemon710 2 года назад

    This has been the best explanation of what if__name__main is and why to use it. Excellent excellent resource. Thank you!!! I will do this from now on. No, I don't wanna go back and change my old stuff! >_

  • @petervakulin3987
    @petervakulin3987 7 месяцев назад

    Every time I decide that it’s time for me to learn Python, I come across something like this and think to myself: “No, thank you, I have enough weirdness in the languages I already know.”

  • @duke4088
    @duke4088 2 года назад +4

    I've had less experience with python as I did most of my coding in Java, C and C++. I've only really used it for ML models in Jupyter until recently. Never really thought about the Global scope issue in importing files as I've never had to bother with that with the other languages - you only ever make a variable global if you explicitly need it to be.
    If this is a problem of global scope in python, then you probably never want to use any global variables, especially in libraries. Good to know.

  • @2k7u
    @2k7u 3 года назад +1

    This gave me a good idea for my C++ Libraries, thanks!

    • @c0smo709
      @c0smo709 3 года назад +1

      Explain please

  • @NerfDave
    @NerfDave 3 года назад

    As a beginner I supposed I’ve ONLY made scripts so far so there hasn’t been much of a reason but I’ll start building the habit now. Thanks for the tip!

  • @IvanNovitskii
    @IvanNovitskii 3 года назад +2

    "public static void Main(string[] args)" spell feels more natural

    • @chrismenza7023
      @chrismenza7023 3 года назад

      nahh im so sick of typing that. Everytime I type that I think to myself I hate this language.

  • @fran9426
    @fran9426 3 года назад +5

    Super informative! I’ve known about using __main__ but never knew about this kind of problem. But it makes me wonder, is there a way to write functions which can only use variables that were passed to it as an argument (or defined within the function)? ie, the variable i was not passed to the function in the video example, so is there a way to have this result in an Error?

    • @mCoding
      @mCoding  3 года назад +2

      Interesting idea! You know I've actually never looked into it before, but as far as I know the language does not support a locals-only directive.

    • @swolekhine
      @swolekhine 3 года назад +1

      Python has a built-in locals() function that will return a dictionary of all the variables that are within only the function's namespace (i.e. not within globals). This includes any arguments passed to the function. You could use '[variable name] in locals()' to get True or False and throw an error accordingly.

    • @rioghander2te
      @rioghander2te 3 года назад +2

      @@swolekhine but that doesn't solve typos like they were shown in this video

    • @fran9426
      @fran9426 3 года назад

      So I guess the move could be to have functions in a separate py file? That would circumvent these types of issues? Not my favorite solution but it sounds like there might not be a clean alternative

    • @yoannguillard6877
      @yoannguillard6877 3 года назад +2

      one_has_a_name = 'Arya'
      def test(plop):
      print(plop, one_has_a_name)
      faceless = types.FunctionType(test.__code__, globals={'print': print})
      faceless('I will raise a name error')

  • @henkfinkers3931
    @henkfinkers3931 2 года назад

    It is always something to find out that there are things like this that I have never done in all my years of using python. I am not going to rewrite all my old code but I will try to apply this in the future.

  • @theawakened7739
    @theawakened7739 3 года назад +4

    YT algorithm boost

    • @mCoding
      @mCoding  3 года назад +1

      This sounds like an energy drink 😋

  • @aks9545
    @aks9545 3 года назад

    Ok, that was very cool. I understood nothing but the fact that if you don't do that, people can import your file and the program doesn't work , and or causes major trouble

  • @technopathioexception9457
    @technopathioexception9457 3 года назад +7

    Discord gang

    • @mCoding
      @mCoding  3 года назад +3

      So much gang activity in my comments!

  • @alexshestakova2220
    @alexshestakova2220 2 года назад

    Thank you, I finally understood the idiom and the benefits of using it.

  • @RayaneS
    @RayaneS 3 года назад +1

    Thanks for that video. This was always so confusing to me. I never thought of all the possibilities of this simple code.

  • @ritiksahu1844
    @ritiksahu1844 3 года назад +3

    Python is said to oop language, but it doesn't even have encapsulation concept

    • @Kyle-xk5ut
      @Kyle-xk5ut 3 года назад

      The comment and the video are both about Python.

    • @ritiksahu1844
      @ritiksahu1844 3 года назад

      @@Kyle-xk5ut yeah I love python

  • @danha3107
    @danha3107 6 месяцев назад

    crazy how so much of professional python dev relies on unenforced unspoken rules and conventions 💀
    granted, it’s a bunch of small, simple, easily understandable conventions but god it’s so easy to forget when there’s already so many, especially if the editor (or ideally the language itself) doesn’t enforce them

  • @herkules593
    @herkules593 2 года назад +1

    I use it whenever I do something serious that I care about breaking or intend to share. Whenever I just script something quickly to maybe edit a csv file or something I don't care about things like that.
    Python for me is a lot about being nice and easy to write some code in to automate a task you don't wanna do manually and I'm not going to make it more involved if not necessary.

    • @stuffit14321
      @stuffit14321 2 года назад

      100%, this is great for it's you intend to reuse or import elsewhere. But if I'm writing a one off 5 liner to parse a text file it's a time waste

  • @arshia.sasson
    @arshia.sasson Год назад

    As a hardware engineer who just dabbles in Python, but I still put if __name__ == '__main__': in my non-script/library files. It allows me easy file-specific debugging when running the file from the spyder terminal. It also lets me prototype/showcase how the file is supposed to be used. Lastly, it saves me the additional files for unittest, but I can still implement that if I so choose.

  • @BRLN1
    @BRLN1 3 года назад

    Well I am using the《If __name__ == "__main__"》ideom for years already, but not the 《def main()》part, because I was not aware of the variables being put to the global scope. Knowing this converted me of course, but this a horrific nightmare. I also just see your video on how future variable initializations do alter python's evaluation behaviour. I guess this video is just another manifestation of that other video's matter.
    I was and still am a huge "fan" of python as it is a convenient and powerful language but these 2 videos changed my mind about python fundamentally.

  • @noisytim
    @noisytim 3 года назад +7

    I feel like unspoken/unwritten rules need to be broken. That kinda "oh, you gotta be a pro to know that" stuff is what keeps people from getting into anything.
    That's why we have the styleguide and enforcements from the interpreter. Anything else just causes more confusion than benefit.

  • @ommpeter
    @ommpeter 9 месяцев назад

    This video successfully talked me out of wanting to become a Python developer

  • @ThePotatoChronicler
    @ThePotatoChronicler 3 года назад +2

    No.

  • @CripsyFries
    @CripsyFries Год назад

    Also you can return a code from the main function, and have a exit statement with code as the return value.

  • @sepehrghafari428
    @sepehrghafari428 3 года назад +1

    Today I faced this problem. Very useful. Thanks!

    • @mCoding
      @mCoding  3 года назад

      You're welcome!