- 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?
What kind of psychopath would put the code in the if block.
Looks at all the Python scripts in my bin folder that I wrote.
Never heard of
def main(): pass if __name__ == '__main__': main()?
I remember how weird this looked the first time I saw it and while I may now understand it, it still looks jank af
Python: I’m so readable that I’m practically executable pseudo-code
Also Python:
if __name__ == '__main__':. . .Now think about this, you have logic that doesn’t make sense when run directly, but you need it to be a library.
You have multiple name=main statements in some of your functions
I’m not sure I’m following the implication. Name=main is for scripts primary, is it not?
I’ve never thought to add more than one of these conditionals anyway…
So you might have a script that does stuff as a library, and it should get environment variables and other info from the calling script. You use the same script for doing one off stuff on different computers.
So you make it do something slightly different or make it set it’s path and look into the current folder when you run it directly. This change in logic could be in a few points in the script.
I still wonder why.
unless it’s for something that you want to work as an importable module and a standalone tool, then why do you need that?
This is exactly why the conditional is used. It allows the script to function both as a standalone application and a library.
ETA: Probably would make sense to just treat it as default behavior in the interpreter and only require the conditional to overwrite in cases where
mainis not the main function and/or pre-processing is needed.Oh that is a good point actually. It’s been a while since I have done any serious Python, so I’m not sure why you couldn’t just use convention instead of this conditional.
For my part, if a Python script is meant to be executed, then I’ll give it a shebang, drop the .py, and simply mark it as executable in the filesystem. 🤷♂️
Heard of it, was too lazy to do it that way.
To be fair I now do it that way, but not when I was learning Python.
What is the point of this?
Not having tons of code in one if statement, but in a function.
And scope. Variables declared in the if can be read everywhere, variables declared in the function are limited to that function.
I thought you were saying to literally use
def main(): pass, that’s why I was confusedOh, no, that’s just the usual placeholder. Though, … would also be valid iirc, and would fit better as a “TODO” placeholder
custom bin folders are a realm no God dares to tread
I can and I do
*trollface*
Why would you waste a function call on something so completely redundant?
~For real though, arg parsing goes in the if, then gets dispatched to whatever function call is needed to run the proper script.~
I definitely do for quick scripts, but I try to break this habit. The biggest advantage of
def main()is that variables are local and not accessible to other functions defined in the same script, which can sometimes help catch bugs or typos.If the file is just a class I usually put example usage with some default arguments in that block by itself. There is no reason for a “main” function. It’s a nice obvious block that doesn’t run when someone imports the class but if they’re looking at the class there is a really obvious place to see the class usage. No confusion about what “main()” is meant to do.
if __name__ == '__main__': # MyClass example Usage my_object = MyClass() my_object.my_method()you can, no one stopping you
I call main() in the if
I always use
if "__main__" == main: __main__()…and earlier in the code:
def __main__(): while True: pass main = "__main__"This helps to prevent people from arbitrarily running my code as a library or executable when I don’t went them to.

Can you elaborate on this blood magic?
It simply swaps some things around to make things more confusing, then goes into an infinite loop (whether or not you import or execute it standalone). it’s no different than just including in the global scope:
while True: passI was kinda lazy with the fuckery, tbh. I could have gotten much more confusing, but don’t have too much time today. :-)
Lol OK I was wondering how would this run
And yes you should!!
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
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.
How do you feel about other peoples Go code?
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.mincluttering 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.
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
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
selectstatement 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.
Go code is always an abomination.
Succinctly and well put.
How many lines are in a page?
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
Bicycleclass, no, that obviously goes inWheeledDeviceServiceFactoryBeanImplthat’s in the ‘utils’ package.Enough of that crazy talk - plainly
WheeledDeviceServiceFactoryBeanImplis where the dependency injection annotations are placed. If you can decide what the code does without stepping through it with a debugger, and any backtrace doesn’t have at least two hundred lines of Spring boot, then plainly it isn’t enterprise enough.Fair enough, though. You can write stupid overly-abstract shit in any language, but Java does encourage it.
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.
Never had the opportunity to work with it. Python is much more pervasive compared to Lua I reckon
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
Php says hello
Still better than having to create a new class just to implement
public static void main(String[] args) {}Relevant Fireship video: https://youtu.be/m4-HM_sCvtQ
Since Java 21, this has been shortened significantly. https://www.baeldung.com/java-21-unnamed-class-instance-main
Only took 27 years to make the Java “Hello, world!” kinda sane.
Free standing functions in Java?! This can’t be true.
I know right? It even has var with implicit typing now. While I prefer Kotlin any day, there’s been quite a few qol improvements to Java over the last few years.
Impossible.
Python people explaining fail to see the point: Yes we know dunders exist. We just want you to say: “Yeah, that is a bit hacky, isn’t it?”
Is it? I really don’t think so. What can you propose that’s better? I think
if __name__ == __main__works perfectly fine and can’t really think of anything that would be better.And you don’t have to use it either if you don’t want to anyway, so no, I don’t think it’s that much of a hack. Especially when the comic compares C as an example, which makes no sense to me whatsoever.
aren’t most of not all conventions hacky anyways?
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
eventandcontext. 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
indeed.
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.
“pythonic”
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.
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
Can someone explain to me how to compile a C library with “main” and a program with main? How does executing a program actually work? It has an executable flag, but what actually happens in the OS when it encounters a file with an executable file? How does it know to execute “main”? Is it possible to have a library that can be called and also executed like a program?
How does executing a program actually work?
Way too long an answer for a lemmy post
It has an executable flag, but what actually happens in the OS when it encounters a file with an executable file?
Depends on OS. Linux will look at the first bytes of the file, either see (ASCII)
#!(called a shebang) or ELF magic, then call the appropriate interpreter with the executable as an argument. When executing e.g. python, it’s going to call/usr/bin/envwith parameterspythonand the file name because the shebang was!/usr/bin/env python.How does it know to execute “main”?
Compiled C programs are ELF so it will go through the ELF header, figure out which
ld.soto use, then start that so that it will find all the libraries, resolve all dynamic symbols, then do some bookkeeping, and jump to_start. That is, it doesn’t:mainis a C thing.Is it possible to have a library that can be called and also executed like a program?
Absolutely.
ld.sois an example of that.. Actually, wait, I’m not so sure any more, I’m getting things mixed up withlibdl.so. In any caseld.sois an executable with a file extension that makes it look like a library.EDIT: It does work. My (GNU) libc spits out version info when executed as an executable.
If you want to start looking at the innards like that I would suggest starting here: Hello world in assembly. Note the absence of a
mainfunction, the symbol the kernel actually invokes is_start, the setup necessary to call a Cmainis done bylibc.so. Don’t try to understand GNU’s libc it’s full of hystarical raisins I would suggest musl.EDIT: It does work. My (GNU) libc spits out version info when executed as an executable.
How does that work? There must be something above
ld.so, maybe the OS? Because looking at the ELF header,ld.sois a shared library “Type: DYN (Shared object file)”$ readelf -hl ld.so ELF Header: Magic: 7f 45 4c 46 02 01 01 03 00 00 00 00 00 00 00 00 Class: ELF64 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - GNU ABI Version: 0 Type: DYN (Shared object file) Machine: Advanced Micro Devices X86-64 Version: 0x1 Entry point address: 0x1d780 Start of program headers: 64 (bytes into file) Start of section headers: 256264 (bytes into file) Flags: 0x0 Size of this header: 64 (bytes) Size of program headers: 56 (bytes) Number of program headers: 11 Size of section headers: 64 (bytes) Number of section headers: 23 Section header string table index: 22 Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flags Align LOAD 0x0000000000000000 0x0000000000000000 0x0000000000000000 0x0000000000000db8 0x0000000000000db8 R 0x1000 LOAD 0x0000000000001000 0x0000000000001000 0x0000000000001000 0x0000000000029435 0x0000000000029435 R E 0x1000 LOAD 0x000000000002b000 0x000000000002b000 0x000000000002b000 0x000000000000a8c0 0x000000000000a8c0 R 0x1000 LOAD 0x00000000000362e0 0x00000000000362e0 0x00000000000362e0 0x0000000000002e24 0x0000000000003000 RW 0x1000 DYNAMIC 0x0000000000037e80 0x0000000000037e80 0x0000000000037e80 0x0000000000000180 0x0000000000000180 RW 0x8 NOTE 0x00000000000002a8 0x00000000000002a8 0x00000000000002a8 0x0000000000000040 0x0000000000000040 R 0x8 NOTE 0x00000000000002e8 0x00000000000002e8 0x00000000000002e8 0x0000000000000024 0x0000000000000024 R 0x4 GNU_PROPERTY 0x00000000000002a8 0x00000000000002a8 0x00000000000002a8 0x0000000000000040 0x0000000000000040 R 0x8 GNU_EH_FRAME 0x0000000000031718 0x0000000000031718 0x0000000000031718 0x00000000000009b4 0x00000000000009b4 R 0x4 GNU_STACK 0x0000000000000000 0x0000000000000000 0x0000000000000000 0x0000000000000000 0x0000000000000000 RW 0x10 GNU_RELRO 0x00000000000362e0 0x00000000000362e0 0x00000000000362e0 0x0000000000001d20 0x0000000000001d20 R 0x1The program headers don’t have interpreter information either. Compare that to
ls“Type: EXEC (Executable file)”.$ readelf -hl ls ELF Header: Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 Class: ELF64 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: EXEC (Executable file) Machine: Advanced Micro Devices X86-64 Version: 0x1 Entry point address: 0x40b6e0 Start of program headers: 64 (bytes into file) Start of section headers: 1473672 (bytes into file) Flags: 0x0 Size of this header: 64 (bytes) Size of program headers: 56 (bytes) Number of program headers: 14 Size of section headers: 64 (bytes) Number of section headers: 32 Section header string table index: 31 Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flags Align PHDR 0x0000000000000040 0x0000000000400040 0x0000000000400040 0x0000000000000310 0x0000000000000310 R 0x8 INTERP 0x00000000000003b4 0x00000000004003b4 0x00000000004003b4 0x0000000000000053 0x0000000000000053 R 0x1 LOAD 0x0000000000000000 0x0000000000400000 0x0000000000400000 0x0000000000007570 0x0000000000007570 R 0x1000 LOAD 0x0000000000008000 0x0000000000408000 0x0000000000408000 0x00000000000decb1 0x00000000000decb1 R E 0x1000 LOAD 0x00000000000e7000 0x00000000004e7000 0x00000000004e7000 0x00000000000553a0 0x00000000000553a0 R 0x1000 LOAD 0x000000000013c9c8 0x000000000053d9c8 0x000000000053d9c8 0x000000000000d01c 0x0000000000024748 RW 0x1000 DYNAMIC 0x0000000000148080 0x0000000000549080 0x0000000000549080 0x0000000000000250 0x0000000000000250 RW 0x8 NOTE 0x0000000000000350 0x0000000000400350 0x0000000000400350 0x0000000000000040 0x0000000000000040 R 0x8 NOTE 0x0000000000000390 0x0000000000400390 0x0000000000400390 0x0000000000000024 0x0000000000000024 R 0x4 NOTE 0x000000000013c380 0x000000000053c380 0x000000000053c380 0x0000000000000020 0x0000000000000020 R 0x4 GNU_PROPERTY 0x0000000000000350 0x0000000000400350 0x0000000000400350 0x0000000000000040 0x0000000000000040 R 0x8 GNU_EH_FRAME 0x0000000000126318 0x0000000000526318 0x0000000000526318 0x0000000000002eb4 0x0000000000002eb4 R 0x4 GNU_STACK 0x0000000000000000 0x0000000000000000 0x0000000000000000 0x0000000000000000 0x0000000000000000 RW 0x10 GNU_RELRO 0x000000000013c9c8 0x000000000053d9c8 0x000000000053d9c8 0x000000000000c638 0x000000000000c638 R 0x1It feels like somewhere in the flow there is the same thing that’s happening in python just more hidden. Python seems to expose it because a file can be a library and an executable at the same time.
Your ld.so contains:Entry point address: 0x1d780EDIT: …with which I meant, modulo brainfart: My
libc.so.6contains a proper entry address, while other libraries are pointing at0x0and coredump when executed.libc.sois a linker script, presumably because GNU compulsively overcomplicates everything.…I guess that’s enough for the kernel. It might be a linux-only thing, maybe even unintended and well linux doesn’t break userspace.
Speaking of, I was playing it a bit fast and loose:
_startis merely the default symbol name for the entry label, I’m sure nasm and/or ld have ways to set it to something different.
If you want to have a library that can also be a standalone executable, just put the main function in an extra file and don’t compile that file when using the library as a library.
You could also use the preprocessor to do it similar to python but please don’t.Just use any build tool, and have two targets, one library and one executable:
LIB_SOURCES = tools.c, stuff.c, more.c EXE_SOURCES = main.c, $LIB_SOURCESEdit: added example
There are a lot of other helpful replies in this thread, so I won’t add much, but I did find this reference, which you could read if you have a lot of free time. But I particularly liked reading this summary:
- _start calls the libc __libc_start_main;
- __libc_start_main calls the executable __libc_csu_init (statically-linked part of the libc);
- __libc_csu_init calls the executable constructors (and other initialisatios);
- __libc_start_main calls the executable main();
- __libc_start_main calls the executable exit().
I haven’t done much low level stuff, but I think the ‘main’ function is something the compiler uses to establish an entry point for the compiled binary. The name ‘main’ would not exist in the compiled binary at all, but the function itself would still exist. Executable formats aren’t all the same, so they’ll have different ways of determining where this entry point function is expected to be. You can ‘run’ a binary library file by invoking a function contained therein, which is how DLL files work.
Shouldn’t the third panel just be empty?
It’s fine like this
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
selfis quite important. The main part of a method is to access the state of the object.selfis 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 } }
Its called
runpy.run_script

















