726

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?

you are viewing a single comment's thread
view the rest of the comments
[-] _stranger_@lemmy.world 2 points 5 days ago

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

[-] bastion@feddit.nl 1 points 5 days ago* (last edited 5 days ago)

Yes, because

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.

Note the "I have the flow of execution", and the "if I want to build a library".

If you just want to build an executable, do as you wish, you already have the flow of execution.

If you want to build a library, make the relevant classes and functions and get out of the way (i.e., no IO, no long-running tasks).

If you want to combine them, use the main name check - or, make a package and do entry points that way. Either way works, because both can fulfill the goal of staying out of the way of those importing this as a library.

this post was submitted on 28 May 2025
726 points (96.3% liked)

Programmer Humor

23627 readers
472 users here now

Welcome to Programmer Humor!

This is a place where you can post jokes, memes, humor, etc. related to programming!

For sharing awful code theres also Programming Horror.

Rules

founded 2 years ago
MODERATORS