DEV Community

Discussion on: How do you order your functions?

Collapse
 
gwutama profile image
Galuh Utama

Python, yes. C/C++, yes (you declare the functions first in header). Bash, yes.

Thread Thread
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

Python?

This does not work. (If you put if __name__ == '__main__': at the bottom, it will work, though.)

But this does work in JavaScript. Don't know whether I should do it, though.

makeBreakfast()

def makeBreakfast():
  addEggs()
  cook()
  serve()


def addEggs():
  print("""
  fridge
    .getEggs()
    .forEach(egg -> fryingPan.add(egg.open());
  """)

def cook():
  print("""
  fryingPan.mixContents();
    fryingPan.add(salt.getABit());
    fryingPan.mixContents();
  """)

def serve():
  print("""
  wife.give(fryingPan.getContents(20, PERCENT));
    self.give(fryingPan.getContents(80, PERCENT)); // huehuehue
  """)
Thread Thread
 
gwutama profile image
Galuh Utama

Well that's true.

if __name__

must be written on the bottom. However here's I always do it in python:

#!/usr/bin/env python

def main():
    foo()

def foo():
    print("foo")
    hello()

def hello():
    print("Hello, world!")

if __name__ == "__main__":
    main()

Ordering functions from the highest abstraction to lower works this way.

Thread Thread
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

It is always nice to see a runnable code, and if possible, IRL open source projects. Thanks.

And I also want to say, this also works regardless of being outer scoped.

#!/usr/bin/env python

def foo():
    print("foo")
    hello()

def hello():
    print("Hello, world!")

if __name__ == "__main__":
    foo()
  • I think main() has no real meaning. But if __name__ == "__main__": as well as anything in __main__.py do. main() may help in unittesting, though.
  • About #!/usr/bin/env python, at least for me, it is rare to make Python only one-file. Often, there are modules, probably with top-level app.py. So, I only put shebang once.
Thread Thread
 
gwutama profile image
Galuh Utama • Edited

Yes, main() is just common to see. By no means it has to be called main().

Here's an example from docker-compose:

The entry point is here

It doesn't even use the usual if __name__ ...

from compose.cli.main import main

main()

which calls this module

Check out the main() function there. It's defined at the top of the file and it calls lower level functions there.

Regarding the hash bang, yes I just do it out of habit. I often use python to replace bash to write small command line tools, which in my case, often in single files.