- cross-posted to:
- programmerhumor@lemmy.ml
- cross-posted to:
- programmerhumor@lemmy.ml
Also, do y’all call main() in the if block or do you just put the code you want to run in the if block?
wait till you see
if __name__ = "__main__": main() `
Luckily Python is one step ahead:
Python 3.13.3 (main, Apr 22 2025, 00:00:00) [GCC 15.0.1 20250418 (Red Hat 15.0.1-0)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> if __name__ = "__main__": ... ... main() ... File "<python-input-0>", line 1 if __name__ = "__main__": ^^^^^^^^^^^^^^^^^^^^^ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
I’ve always found needing to manually add a class instance parameter (i.e.
self
) to every object method really weird. And the constructors being named__init__
. Not having multiple dispatch is kinda annoying too. Needing to use decorators for class methods, static methods, and abstract classes is also annoying. Now that I think about it, Python kinda sucks (even though it’s the language I use the most, lol).Nah
self
is quite important. The main part of a method is to access the state of the object.self
is just the interface to it.Guess I just prefer languages that do it this way:
class AClass { var aProp = 0 fun aMethod() { aProp++ } }
Though I suppose confusion and bugs can happen when you do something like:
class AClass { var aProp = 0 fun aMethod(aProp: Int) { // `this.aProp` is needed to access the property } }
Depends on how lazy I am at the moment.
main.py
or did you not read the manual?The if block is where my arg parser goes
Does everyone call the function of the script main? I never use main(), just call the function what the program is supposed to do, this program calculates the IBNR? The function is called calculate_IBNR(), then at the end of the script if name = ‘main’: calculate_IBNR(test_params) to test de script, then is imported into a tkinter script to be converter to an exe with pyinstaller
All of mine are called
do_thing()
because after a few days of working on it, the scope creep always means the original name was wrong anyway.
I would put my code in a
def main()
, so that the local names don’t escape into the module scope:if __name__ == '__main__': def main(): print('/s') main()
(I didn’t see this one yet here.)
I’m a little new to Python standards. Is this better or worse than putting the
def main():
outside the if statement (but callingmain()
inside it)I intended this an sarcastic example; I think it’s worse than putting the main outside of the branch because of the extra indent-level. It does have an upside that the
main()
doesn’t exist if you try import this as an module.I thought confusion about indent levels was the whole point of using python
But it feels like main function should not be indented
Could someone explain this please? I’m still a noob.
All code needs to have an entry point.
For Python and some other languages, this is the start of the file.
For other languages, this is a special function name reserved for this purpose - generally, “main”.
In the first kind of language, the thought process is basically: I have the flow of execution, starting at the top of the file. If I want to make a library, I should build the things I want to build, then get out of the way.
In the other kind of language, the thought process is basically: I am building a library. If I want to make an executable, I should create an entry point they the execution starts at.
The debate is honestly pretty dumb.
Python doesn’t need the name main check to function at all. that’s just a convenience feature that lets developers also include arbitrary entry points into modules that are part of a library and expected to be used as such. If you’re writing a script, a file with a single line in it reading
print("hello world")
will work fine when run:python thescript.py
Basically, when you compile a program written in Rust or C/C++ (the first and second panels respectively), the compiler needs to know what’s supposed to be executed first when the program is run directly (i.e. when you click on the executable), which in these languages, is denoted by a special function called
main()
. Executable files can also contain functions and data structures that can be called by other programs, and when they are, you wouldn’t want to run an entire complex and resource intensive program if another program only needs to call a single function from it, so in that case the other program will call the function it wants but not main, so only that function executes and not the entire program.However, Python is a scripting language that’s interpreted. So every Python source file is executable provided you have the Python runtime. Python also doesn’t have native support for main functions in the same way Rust and C/C++ does, and it will execute every line of code as it reads the source file. This is why a single line Python file that just calls print is valid, it doesn’t need to be wrapped in a main function to execute. However, what if your Python file is both meant to be executed directly and provides functions that other Python files can call? If you just put the main routine in the root of the file, it would be executed every time another program tries to import the file in order to call functions from it, since the import causes the file to be interpreted and executed in its entirety. You can still just have a main function in your file, but since Python doesn’t natively support it, your main function won’t do anything if you run the file directly because as far as Python is concerned, there is no executable code at the root of the file and you haven’t called any functions.
The workaround is to have a single if statement at the root of the file that looks like this:
if __name__ == '__main__': main()
It checks a special variable called
__name__
. If the Python file is directly executed,__name__
will have the value of the string'__main__'
, which satisfies the if statement so main() is called. If another Python file is calling a function, the value of__name__
will be the name of that file, so main() is not called. It’s clunky and not that efficient, but, 1, it works, and 2, if you cared about efficiency, you wouldn’t be writing it in Python.Really helpful explanation, thanks.
thats why i name my modules main.py
Python has a bunch of magic variables, like
__name__
. This one contains the name of the module you’re currently in (usually based on the file name), so if your file is calledfoo.py
, it will have the valuefoo
.But that’s only if your module is being imported by another module. If it’s executed directly (e.g.
python foo.py
), it will instead have a__name__
of__main__
. This is often used to add a standalone CLI section to modules - e.g. the module usually only defines functions that can be imported, but when executed it runs an example of those functions.Really helpful explanation, thanks.
checks username
So it’s you they’re always talking about
It is, it’s the other Barry.
The
if
block is still in the global scope, so writing the code in it is a great way to find yourself scratching your head with a weird bug 30 minutes later.One thing I really dislike about Python is the double underscore thing, just really looks ugly to me and feels excessive. Just give me my flow control characters that aren’t whitespace
I’m at peace with balanced underscores (like “dunder name equals dunder main”) and the internal ones for snake case, but in the unbalanced ones (prefixing unders and dunders for pseudo-private) still bug me. But at least, conventionally, it’s visually the same idea as Hungarian notation.
Php says hello
I use if__name__main__ often when working with AWS Lambda, but I also want to run it locally. Lambda wants to call a function with the params
event
andcontext
. So I would do something like this:def handler(event, context): things return { 'statusCode': 200, 'body': 'Hello from Lambda!' } if __name__ == '__main__': event = {} context = {} response = handler(event, context) print(response)
Diabolical
isn’t that just normal usage? …or, did I just whoosh and you were sarcastically saying that?
It is normal usage. Though personally I’d probably make another “main” function, to avoid declaring a bunch of global variables
Yeah. I like using
main()
that way too. It’s usually just a high-level function that handles globals relevant to running in standalone and calling other functions to do work.
Alternative: put entry point code in file
__main__.py
& run the containing package (eg,some_package
) as a top-level expression (eg,python -m some_package
).TIL. Thanks for that!
Sometimes I have the misfortune of working with python code written by someone else and I wonder how a language like this became anything more than a scripting language
Sounds like a skill issue on your end
Agreed. I program mainly in C so its easier for me to make sense of bad C code than bad python code which just makes me cry
Does Lua rank far below python for you? I have so much rage against it. At least with Python I don’t have to do a bunch of steps to just get it to do something. May take me a while to get through bad Python code, but Lua makes my eyes bleed and I begin to regret my life choices in trying to understand wtf these people wrote.
I feel that Python is a bit of a ‘Microsoft Word’ of languages. Your own scripts are obviously completely fine, using a sensible and pragmatic selection of the language features in a robust fashion, but everyone else’s are absurd collections of hacks that fall to pieces at the first modification.
To an extent, ‘other people’s C++ / Bash scripts’ have the same problem. I’m usually okay with ‘other people’s Java’, which to me is one of the big selling points of the language - the slight wordiness and lack of ‘really stupid shit’ makes collaboration easier.
Now, a Python script that’s more than about two pages long? That makes me question its utility. The ‘duck typing’ everywhere makes any code that you can’t ‘keep in your head’ very difficult to reason about.
other people’s Java
I’m gonna have to disagree here, it’s always a guessing game of how many layers of abstraction they’ve used to seemingly avoid writing any implementation code… Can’t put the code related to “bicycles” in the
Bicycle
class, no, that obviously goes inWheeledDeviceServiceFactoryBeanImpl
that’s in the ‘utils’ package.How many lines are in a page?
How do you feel about other peoples Go code?
I used it for a while and I think it’s been one of the best languages I’ve tried. C for example is too barebones for modern desktop apps. Apps written in Rust are great but most of the time, it’s just not worth the effort. And stuff like Python, JS is… uhh… where do I even begin
I think Go hits the sweet spot between these. Unlike C, it at least has some simple error/panic mechanism, GC so you don’t have to worry about memory much and some modern features on top of that. And unlike Python it can actually create reasonably snappy programs.
In any programming language, there will always be multiple cases where you need to link C libraries. CGo, although people don’t seem to be adoring it, is actually… okay? I mean of course it does still have some overhead but it’s still one of the nicer ways to link C libraries with your code. And Go being similar to C makes writing bindings so much easier
Multithreading in Go is lovely. Or as I read somewhere “you merely adopted multithreading, I was born with it”
Packaging is handled pretty nicely, pulling a library from the net is fairly trivial. And the standard directory structure for Go, although I’m not used to it, makes organizing stuff much easier and is easy to adopt
As you would’ve guessed from the amount of times I mentioned C in this comment, I basically see Go as the “bigger C for different situations”
Well now. My primary exposure to Go would be using it to take first place in my company’s ‘Advent of Code’ several years ago, in order to see what it was like, after which I’ve been pleased never to have to use it again. Some of our teams have used it to provide microservices - REST APIs that do database queries, some lightweight logic, and conversion to and from JSON - and my experience of working with that is that they’ve inexplicably managed to scatter all the logic among dozens of files, for what might be done with 80 lines of Python. I suspect the problem in that case is the developers, though.
It has some good aspects - I like how easy it is to do a static build that can be deployed in a container.
The actual language itself I find fairly abominable. The lack of exceptions means that error handling is all through everything, and not necessarily any better than other modern languages. The lack of overloads means that you’ll have multiple definitions of eg.
Math.min
cluttering things up. I don’t think the container classes are particularly good. The implementation of pointers seems solely implemented to let you have null pointer exceptions, it’s a pointless wart.If what you’re wanting to code is the kind of thing that Google do, in the exact same way that Google do it, and you have a team of hipsters who all know how it works, then it may be a fine choice. Otherwise I would probably recommend using something else.
I’m now 1 year in to working in Go having been mostly C++ and then mostly large-scale Python dev (with full type annotation).
Frankly, I bristle now at people giving Python a hard time, having worked with Go and I now hate Go and the de-facto ethos that surrounds it. Python may be slow, but for a lot of use cases not in any way that matters and modern computers are very fast. Many problem areas are not performance-limited, and many performance problems are algorithmic, not from raw statement execution. I even rewrote an entire system in Python and made it use 20% of the CPU the former C++ solution used, while having much more functionality.
The error returns drive me nuts. I looked around for explanations of the reasoning as I wasn’t seeing it, and only found bald assertions that exceptions get out of control and somehow error returns don’t. Meanwhile standard Go code is very awkward to read because almost every little trivial function calls becomes 4 lines of code, often to do nothing but propagate the error (and errors are just ignored if you forget…). With heavy use of context managers, my error and cancellation handling in Python was always clean, clear, and simple, with code that almost read like whiteboard pseudo-code.
The
select
statement can be cool in Go, but then you realize that literally 98% of the times it’s used, it’s simply boilerplate code to (verbosely) handle cancellation semantics via the context object you have to pass everywhere. Again, literally code you just don’t need in exception-based languages with good structures to manage it like Python context managers.And every time you think “this is stupidly awkward and verbose, surely there’s a cleaner way to do this” you find people online advocating writing the same boilerplate code and passing it off as a virtue. e.g. get a value from a map and fall back to a default if it’s not there? Nope, not offering that, so everyone must write their own
if foo, ok := m[k]; !ok {...}
crap. Over and over and over again the answer is “just copy this chunk of code” rather than “standard libraries should provide these commonly needed utilities”. Of course we can do anything we want ourselves, it’s Turing Complete, but why would we want to perpetually reinvent these wheels?It’s an unpopular language, becoming less popular (at least by Google trends) and for good reason. I can see it working well for a narrow set of low level activities with extreme concurrency performance needs, but it’s not the only language that could handle that, and for everything else, I think it’s the wrong choice.
This is the most excellent summary of Go I have ever read. I agree with everything you’ve said, although as a fan of Scala and in particular its asynchronous programming ecosystem (cats for me, but I’ll forgive those who prefer the walled garden of zio) I would also add that, whilst its async model with go routines is generally pretty easy to use, it can shit the bed on some highly-concurrent workloads and fail to schedule stuff in time that it really should’ve, and because it’s such a mother-knows-best language there’s fuck all you can do to give higher priority to the threads that you happen to know need more TLC
Go code is always an abomination.
Call the function from the if block.
Now your tests can more easily call it.
I think at my last job we did argument parsing in the if block, and passed stuff into the main function.