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

  Рет қаралды 1,391,316

mCoding

mCoding

Күн бұрын

Python's favorite unexplained incantation!
Do you know def main if _name_ == '__main__'? In this video I explain why your Python scripts should use this idiom. It's not strictly necessary, but you will be a better Python coder if you follow established conventions that improve the readability of your code.
― mCoding with James Murphy (mcoding.io)
Source code: github.com/mCodingLLC/VideosS...
StackOverflow on the topic: stackoverflow.com/questions/4...
Python docs: docs.python.org/3/reference/t...
SUPPORT ME ⭐
---------------------------------------------------
Patreon: / mcoding
Paypal: www.paypal.com/donate/?hosted...
Other donations: mcoding.io/donate
Top patrons and donors:
Jameson, John M, Laura M, Pieter G, Vahnekie, Sigmanificient
BE ACTIVE IN MY COMMUNITY 😄
---------------------------------------------------
Discord: / discord
Github: github.com/mCodingLLC/
Reddit: / mcoding
Facebook: / james.mcoding
CHAPTERS
---------------------------------------------------
0:00 Intro
0:58 Dunder name
1:47 Why if name main
3:36 Why def main
4:59 Pickle example
5:42 Multiprocessing example
6:42 Main function entry point
7:07 Outro

Пікірлер: 1 000
@stevenalexander6262
@stevenalexander6262 2 жыл бұрын
I've used python for a while now, and I had no clue about the unwritten rules. Thanks for this
@mCoding
@mCoding 2 жыл бұрын
Glad it was helpful!
@AkosLukacs42
@AkosLukacs42 2 жыл бұрын
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 2 жыл бұрын
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 2 жыл бұрын
@@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 2 жыл бұрын
@@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.
@megaing1322
@megaing1322 2 жыл бұрын
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 2 жыл бұрын
Interesting point! I hadn't considered that but I suppose it is yet another benefit of avoiding globals.
@BRLN1
@BRLN1 2 жыл бұрын
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 2 жыл бұрын
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 2 жыл бұрын
ya smoked some serius cpython sources
@leftaroundabout
@leftaroundabout 2 жыл бұрын
@@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.
@StephenRoseDuo
@StephenRoseDuo 2 жыл бұрын
Reminding me about global variables converted me
@mCoding
@mCoding 2 жыл бұрын
Then the video was a success!
@thoperSought
@thoperSought 2 жыл бұрын
me too
@IqweoR
@IqweoR 2 жыл бұрын
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 2 жыл бұрын
@@IqweoR hahahaha, that's so true
@rubenduarte1468
@rubenduarte1468 2 жыл бұрын
As someone just starting to learn Python, this gave me a headache :) I have so much to learn...
@abdullahnadeem1823
@abdullahnadeem1823 2 жыл бұрын
Don't worry, you'll make it. Although, im nothing special myself
@pdc5210
@pdc5210 2 жыл бұрын
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 2 жыл бұрын
Don't worry, as long as you believe in yourself, nothing can stop you!
@nebster333
@nebster333 2 жыл бұрын
this is me :D let's not give up!
@chrishofer6370
@chrishofer6370 2 жыл бұрын
Same...
@aleksanderkrauze9304
@aleksanderkrauze9304 2 жыл бұрын
This flashing "captions" are VERY funny. Keep 'em coming!
@mCoding
@mCoding 2 жыл бұрын
Thanks! I wasn't sure if people would like them or find them annoying! Anyone reading please do let me know!
@joseflat
@joseflat 2 жыл бұрын
@@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 2 жыл бұрын
@@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 2 жыл бұрын
@@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 2 жыл бұрын
@@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.
@zacbailey6112
@zacbailey6112 2 жыл бұрын
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 жыл бұрын
Thanks for the kind words!
@hossumquat
@hossumquat 2 жыл бұрын
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.
@pefu512
@pefu512 2 жыл бұрын
You could have also mentioned "test driven programming": In test driven programming first some test code is written, which will check whether the main() function does what it is supposed to do. Having all important code in functions is needed to make it callable from those outside test modules. pytest is a great library which aids the test driven approach to programming.
@MaazAhmed
@MaazAhmed 2 жыл бұрын
I'm new to programming and I did come across projects that rely on this. Where do you think I can learn more about this test driven approach, specifically for python?
@pefu512
@pefu512 2 жыл бұрын
@@MaazAhmed use your favorite search engine 😉
@MaazAhmed
@MaazAhmed 2 жыл бұрын
@@pefu512 haha thought you might know any useful resources, but of course, the search engine's always there. :)
@scifino1
@scifino1 2 жыл бұрын
@@MaazAhmed My recipe for test driven development (aka TDD) is: 1. Plan your project and define its use-cases 2. Your use-case definitions should be as detailed and precise as possible. Particularly, they should define which inputs under which conditions should produce which outputs. E.g. "If the function log() is called with the parameters 'foo' and 'bar', after its execution there should be a file called 'foo.log' containing the text 'bar'." 3. From these definitions derive the API that you want to test. In the above case, this would be the function log(). As you can see, it should take two parameters of type str (in Python), so its function head should look something like "def foo(filename: str, content: str) -> None:". 4. Add dummy implementations (just the function head + the pass-keyword) in the place where you plan to do the actual implementation 5. Implement your tests so that they call the dummy implementation. One test per use-case should be enough, but you need to identify all use-cases. I.E. maybe the output should be a thrown exception if the user inputs None instead of a str. That would be another use-case. 6. Replace the pass-keyword with the actual implementation and use your already implemented tests, to ensure correctness.
@emurphy42
@emurphy42 2 жыл бұрын
@@scifino1 To clarify, the point of step 5 is to verify that the tests fail when calling the dummy functions, then step 6 verifies that they pass when calling the real ones. Thus, the test is actually correctly testing both sides of what it’s supposed to test. For use cases where doing nothing is the correct behavior, the dummy functions should do something (probably something that would be correct if the inputs had been different).
@spacehooliganzack7429
@spacehooliganzack7429 2 жыл бұрын
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
@zTJq40sl
@zTJq40sl 2 жыл бұрын
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.
@susu5331
@susu5331 2 жыл бұрын
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!
@garfbuckle9081
@garfbuckle9081 Жыл бұрын
british
@ianrickey208
@ianrickey208 2 жыл бұрын
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 2 жыл бұрын
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!
@Shynaku
@Shynaku Жыл бұрын
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.
@pinkdiscomosh2766
@pinkdiscomosh2766 2 жыл бұрын
Really cool tip. As someone who just uses python as a hobby language, little tips like these are super helpful. Thanks
@kruksog
@kruksog 2 жыл бұрын
I was always taught to do this and never understood exactly why, so this was nice to learn.
@mensaswede4028
@mensaswede4028 2 жыл бұрын
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 жыл бұрын
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 жыл бұрын
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 жыл бұрын
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.
@onakitokiful
@onakitokiful Жыл бұрын
@@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 Жыл бұрын
@@onakitokiful you mean lower?
@esmith2k2
@esmith2k2 2 жыл бұрын
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
@jjbankert
@jjbankert 2 жыл бұрын
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 2 жыл бұрын
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 2 жыл бұрын
@@foodice11 and with the main() call at the very bottom that's no problem
@chiefmofo
@chiefmofo Жыл бұрын
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.
@ironbard4901
@ironbard4901 2 жыл бұрын
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 2 жыл бұрын
Great to have you watching!
@quamrana
@quamrana 2 жыл бұрын
Great tip about "name main" in PyCharm. I'm going to use that for every script from now on!
@dwarakanandan
@dwarakanandan 2 жыл бұрын
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.
@kiritoasuna8602
@kiritoasuna8602 2 жыл бұрын
Wow, this is quality content. This channel is going big, mark my word.
@johnrussell6971
@johnrussell6971 Жыл бұрын
This video really *underscores* the importance of if __name_- == "__main__". Nicely done!
@TheDarkOne629
@TheDarkOne629 Жыл бұрын
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. :)
@atrus3823
@atrus3823 2 жыл бұрын
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.
@RayaneS
@RayaneS 2 жыл бұрын
Thanks for that video. This was always so confusing to me. I never thought of all the possibilities of this simple code.
@danielmajer1648
@danielmajer1648 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!
@FloatingSunfish
@FloatingSunfish 2 жыл бұрын
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.
@NewspireMakes
@NewspireMakes 2 жыл бұрын
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 2 жыл бұрын
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 жыл бұрын
@@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...
@Zokrar
@Zokrar 2 жыл бұрын
These are the types of videos I love! It's nice understanding the why of some less obvious things.
@mCoding
@mCoding 2 жыл бұрын
Glad you liked!
@gempf
@gempf 2 жыл бұрын
you are so quick, you make me feel that I don't know about Python at all, thanks for the video
@mCoding
@mCoding 2 жыл бұрын
Continue watching and I will bring you up to my level in time!
@bendirval3612
@bendirval3612 2 жыл бұрын
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 4 ай бұрын
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 4 ай бұрын
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.
@1234admir
@1234admir 2 жыл бұрын
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 жыл бұрын
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 жыл бұрын
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 жыл бұрын
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 жыл бұрын
@@aba22125 You didn't understand it, becasue you didn't use classes/functions?
@always-ask-why
@always-ask-why 2 ай бұрын
This is the best and most complete explanation I've seen on this question.
@Innosos
@Innosos 2 жыл бұрын
My god you make this sound so logical and obvious. I wonder if this stuff is related to some excessive RAM allocation issues I've been having with Python. Thank you!
@re.liable
@re.liable 2 жыл бұрын
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 2 жыл бұрын
The feeling goes away fast if you ever waste an hour due to one of the issues!
@farris8503
@farris8503 2 жыл бұрын
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 2 жыл бұрын
@@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 2 жыл бұрын
@@farris8503 Same here from Java
@manonthedollar
@manonthedollar 2 жыл бұрын
Man, thank you. In my last job, people complained that my scripts were overly-complicated, and pointed at things like defining a main() function instead of just putting it in if __name__=="__main__". I still feel defensive every time I do it but it definitely rocked my self confidence.
@mCoding
@mCoding 2 жыл бұрын
Don't let those people get to you :). Even if using a main function didn't prevent all the subtle errors I talked about in this video, taking a chunk of code and refactoring it into a function is usually associated with *simplifying* code, not complicating it. Adding in a single function should not be too complex an operation by any reasonable coder's standard. Of course, if someone didn't make a main function and just used the if check, I probably wouldn't complain.
@dragonsage6909
@dragonsage6909 2 жыл бұрын
This was awesome, rewatching and rewriting my default tmp code block.. thank you!
@mCoding
@mCoding 2 жыл бұрын
Very welcome!
@aaronjameshorne
@aaronjameshorne 2 жыл бұрын
Watched several videos and this one was to the point and clear! thank you.
@BlackHermit
@BlackHermit 2 жыл бұрын
I already use this all the time! :)
@lepsycho3691
@lepsycho3691 2 жыл бұрын
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 жыл бұрын
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 Жыл бұрын
@@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
@tnczm
@tnczm 2 жыл бұрын
Super helpful. I've seen the idiom many times, but wasn't really aware of the implications. Makes perfect sense now ;)
@mCoding
@mCoding 2 жыл бұрын
Great to hear!
@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.
@You-qe6qb
@You-qe6qb 2 жыл бұрын
"C programmers know", yes that was like a personal attack
@bobchannell3553
@bobchannell3553 2 жыл бұрын
There's a very good Corey Schafer video from 2015 that explains this very well. It doesn't talk about the global variables though.
@pranavnigam11
@pranavnigam11 2 жыл бұрын
the reason at the end convinced me to use the def main part too
@alexshestakova2220
@alexshestakova2220 Жыл бұрын
Thank you, I finally understood the idiom and the benefits of using it.
@EnternodeCS
@EnternodeCS 2 жыл бұрын
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 2 жыл бұрын
*always bugged me
@alexjusto9591
@alexjusto9591 2 жыл бұрын
What's wrong with defining a function and calling it like this?
@EnternodeCS
@EnternodeCS 2 жыл бұрын
@@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
@nottheengineer4957
@nottheengineer4957 2 жыл бұрын
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 жыл бұрын
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!
@thoperSought
@thoperSought 2 жыл бұрын
I was just starting to do this partly because I am trying to learn unit testing, and I thought it would be best to have the tests in a separate file, which I would then import the code I want to test into. I had never seen the idiom of calling a main function from the fenced block, though. the namespace argument convinced me to start doing it that way.
@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!
@OshalevshiyKeks
@OshalevshiyKeks 2 жыл бұрын
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 2 жыл бұрын
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 =)))
@sicus0
@sicus0 2 жыл бұрын
The shebang is also a must in (Python) scripts.
@12345origamimaster
@12345origamimaster 2 жыл бұрын
Even if you are on windows ;)
@bersK00
@bersK00 2 жыл бұрын
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 2 жыл бұрын
@@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.
@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!
@antondjayzakov4776
@antondjayzakov4776 2 жыл бұрын
this video, discovers very important thing to know. Didn't realized until I saw it. 💯 thank you 🙏
@josephcohen734
@josephcohen734 2 жыл бұрын
I don't use it cuz it makes my code too readable and doesn't give enough juicy bugs
@nathanwise9271
@nathanwise9271 2 жыл бұрын
Your videos are always great
@mCoding
@mCoding 2 жыл бұрын
I appreciate that! Thanks for watching!
@tributontenkaiiceblast2646
@tributontenkaiiceblast2646 2 жыл бұрын
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!
@Pope_
@Pope_ 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 :)
@davidyu1813
@davidyu1813 2 жыл бұрын
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
@Vousie
@Vousie 2 жыл бұрын
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 2 жыл бұрын
Yeah, I do it in my more serious projects. For sketches I usually just blindly write anything just the way it is
@Davide73
@Davide73 Жыл бұрын
Is this a joke? In a "larger python programs" you are having this approach??
@Luca-re3ve
@Luca-re3ve 2 жыл бұрын
I've been using python in my university career and i didn't knew bout that, very useful video and definitely a good habit. I'm gonna use it for sure :)
@deemon710
@deemon710 Жыл бұрын
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! >_
@juliejones8785
@juliejones8785 2 жыл бұрын
Using a main function also allows unit testing with pytest
@FirstLast-kv1iq
@FirstLast-kv1iq 2 жыл бұрын
non discord but youtube notification gang
@mCoding
@mCoding 2 жыл бұрын
Welcome!
@hugoavila5049
@hugoavila5049 3 ай бұрын
Damn im so glad i was patient enough to wait to come across your video… thank you appreciate the wisdom🙏
@michaelcamp2870
@michaelcamp2870 Жыл бұрын
Thanks for this video! The stuff about unintentionally creating global variables was especially illuminating for this programming newbie. 😄
@TigerWalts
@TigerWalts 2 жыл бұрын
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 2 жыл бұрын
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 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.
@johncip
@johncip 2 жыл бұрын
You're better off distinguishing between library modules (imported but not run) and scripts (run but not imported). Then the problem goes away with no need to write extra code. Reminds me of fixing a function getting unexpected null inputs by setting them to a non-empty default -- by guarding against the symptom, you make the root of the illness harder to spot later on. More generally, it's a bad idea to see something happening that "Should Never Happen," and then paper over it with a conditional. (Yes, I know "if main" is conventional in Python. So is the use of exceptions for control flow. Bad ideas are usually popular, and that goes double for Python.)
@wojciechwilimowski985
@wojciechwilimowski985 2 жыл бұрын
I'm a .NET dev, but now I know why I do the thing I saw everyone do in pro Python code. Thanks!
@aba22125
@aba22125 2 жыл бұрын
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.
@AnweshGangula
@AnweshGangula 2 жыл бұрын
Additional advantage of this is you can organize the functions in any order.
@robertolin4568
@robertolin4568 2 жыл бұрын
I like how straight-forward Python is, but conventions like this, along with tragic package management are really against the Zen of Python.
@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.
@rolando1259
@rolando1259 2 жыл бұрын
I always do this in Python! Great video
@silversurfer8057
@silversurfer8057 2 жыл бұрын
I'm very new to python (not programming). before i had some prejudices but currently i have to say that python is much better than expected. nevertheless the code style is a new world (so videos like this are really helpful here). What I would be interested in is the following: it is great that you can execute every script - so sometimes I write a test function directly under a library function. the problem is that the import of other components is often not working because the starting point in the folder structure is different (because the library-funktion is not in the same folder with the main-script). is there a best practice for this?
@__lasevix_
@__lasevix_ Жыл бұрын
(here for the notification, SO failed me)
@GrantGryczan
@GrantGryczan Жыл бұрын
I'm a bit late, but I'm not sure I understand what you're asking
@alfeberlin
@alfeberlin 2 жыл бұрын
I even recommend this idiom: if ___name___ == '__main__': import sys # only necessary if not yet imported of course sys.exit(main(sys.argv)) This way you can easily write unit test cases for testing your main() function as well and don't need to mock sys.argv or sys.exit(). The main() function then only is supposed to use its argument instead of the global sys.argv and it also just is supposed to return an exit value instead of using sys.exit directly. This also allows wrapping the main() function in some weird cases (call it from somewhere) without too much trouble.
@evadeflow
@evadeflow Жыл бұрын
Yup. I was gonna reply and say the same thing, seems sensible to exit with a value. I usually also have a try/except block around ‘sys.exit(main())’ that exits non-zero if an uncaught exception bubbles up. This is critical for utility scripts used in CI and other ‘headless’ setups, otherwise how can you tell if it failed?
@codingstation7741
@codingstation7741 2 жыл бұрын
This is great info. Thanks!
@fran9426
@fran9426 2 жыл бұрын
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 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 2 жыл бұрын
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 2 жыл бұрын
@@swolekhine but that doesn't solve typos like they were shown in this video
@fran9426
@fran9426 2 жыл бұрын
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 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')
@bobchannell3553
@bobchannell3553 2 жыл бұрын
Of course there's a reason to do it. We want to make Python as complicated as Java or C++.
@mCoding
@mCoding 2 жыл бұрын
Ahh yes, the language flex argument.
@U20E0
@U20E0 2 жыл бұрын
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 2 жыл бұрын
@@U20E0 Can do in C++ too...
@JohnnyLifts69
@JohnnyLifts69 5 ай бұрын
Aiight I'm sold. Well explained
@thedrunknmunky6571
@thedrunknmunky6571 2 жыл бұрын
Funny and informative. Keep it up!
@duke4088
@duke4088 2 жыл бұрын
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.
@vsolyomi
@vsolyomi 2 жыл бұрын
"flashbacks to learning java" - oh yeah, I feel your pain!
@daviddumon4020
@daviddumon4020 Жыл бұрын
This was very clear, thank you
@carlynghrafnsson4221
@carlynghrafnsson4221 Жыл бұрын
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.
@KangJangkrik
@KangJangkrik 2 жыл бұрын
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
@hung-tienhuang3640
@hung-tienhuang3640 2 жыл бұрын
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 2 жыл бұрын
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 2 жыл бұрын
@@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 2 жыл бұрын
@@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.
@tenaciouspete
@tenaciouspete Жыл бұрын
Thanks so much for explaining this. You are a legend.
@2k7u
@2k7u 2 жыл бұрын
This gave me a good idea for my C++ Libraries, thanks!
@c0smo709
@c0smo709 2 жыл бұрын
Explain please
@fosspointer
@fosspointer 2 жыл бұрын
watching this as a c++ programmer who's never worked with python before
@senhalil
@senhalil 2 жыл бұрын
I'll be honest not having "you" at the corner let me focus on the subject a lot better.
@mCoding
@mCoding 2 жыл бұрын
😳
@parkerkeller9778
@parkerkeller9778 2 жыл бұрын
@@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 2 жыл бұрын
@@mCoding nah keep the facecam, you have an awesome face
@thepurplesmurf
@thepurplesmurf 2 жыл бұрын
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.
@user-bx9nf2ph6w
@user-bx9nf2ph6w 2 жыл бұрын
great explanation, thank you!
@NerfDave
@NerfDave 2 жыл бұрын
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!
@Luclecool123
@Luclecool123 2 жыл бұрын
Just so you know f"__name__={__name__}" can be written like f"{__name__=}"
@DanTheManTerritorial
@DanTheManTerritorial 2 жыл бұрын
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
@danielvillegas7013
@danielvillegas7013 2 жыл бұрын
0:15 When you create a library that defines the meaning of the universe
@mCoding
@mCoding 2 жыл бұрын
That's gonna be one popular library!
@scfog90
@scfog90 2 жыл бұрын
That's the function deep thought calculated in billions of years... and it's brilliant. Mathematicians say, the easiest looking solutions are the most advanced and elegant ones
@saidzihmmou6426
@saidzihmmou6426 2 жыл бұрын
thank you, very clear explanation!
@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 жыл бұрын
Presumably you want to know *why* you should do this and hear the reasons rather than blindly following advice from the internet. 🙃
@technopathioexception9457
@technopathioexception9457 2 жыл бұрын
Discord gang
@mCoding
@mCoding 2 жыл бұрын
So much gang activity in my comments!
5 Good Python Habits
17:35
Indently
Рет қаралды 284 М.
If __name__ == '__main__' for Python Beginners
9:29
Indently
Рет қаралды 15 М.
Этого От Него Никто Не Ожидал 😂
00:19
Глеб Рандалайнен
Рет қаралды 10 МЛН
YouTube's Biggest Mistake..
00:34
Stokes Twins
Рет қаралды 46 МЛН
super/MRO, Python's most misunderstood feature.
21:07
mCoding
Рет қаралды 209 М.
The Fastest Way to Loop in Python - An Unfortunate Truth
8:06
mCoding
Рет қаралды 1,3 МЛН
21 MORE nooby Python habits
9:55
mCoding
Рет қаралды 110 М.
25 nooby Python habits you need to ditch
9:12
mCoding
Рет қаралды 1,7 МЛН
Unlocking your CPU cores in Python (multiprocessing)
12:16
mCoding
Рет қаралды 287 М.
Python's 5 Worst Features
19:44
Indently
Рет қаралды 58 М.
Python dataclasses will save you HOURS, also featuring attrs
8:50
If __name__ == "__main__" for Python Developers
8:47
Python Simplified
Рет қаралды 373 М.
3 PYTHON AUTOMATION PROJECTS FOR BEGINNERS
17:00
Internet Made Coder
Рет қаралды 1,4 МЛН
ИГРОВОЙ ПК от DEXP за 37 тысяч рублей из DNS
27:53
Why spend $10.000 on a flashlight when these are $200🗿
0:12
NIGHTOPERATOR
Рет қаралды 17 МЛН