Hi all,

I see a lot of books teaching beginning Python students to code like this:

def func1():
  ...

def func2():
  ...

class Blah(object):
  ...

def main():
  ...

main()

It strikes me that having people "def main():" and then call main() is a bit silly. In fact, it seems to be nothing more than a hold-over from C/C++.

My main gripe (heh, get it? "main"! I'm killin' 'em) with it is this: when my code breaks, I like to be able to inspect the values of variables. But if all of my code is enclosed in "main()", then the variables have all since gone out of scope and aren't available to be inspected.

So on a pragmatic level, I oppose the "def main():" style for the simple reason that it makes debugging a bit harder.

Are there any reasons that I should reconsider my dislike for "def main():"?

Thanks,
Jeff

I am with you Jeff, looks a lot like C. Who needs that old stuff?

One of the reasons for encompassing most of your code in a function, it does not have to be main, but many choose to use main, is that it allows you to use this idiom of having your program also act as a module:

if __name__ == '__main__':
  main()
# else:
  # its imported as a module

I don't see any extra problems when debugging. I can set breakpoints etc OK.

- Paddy.

That's true; one can always use the debugger. But for some things ... like GUI programming ... the debugger is a bit dicey.

I agree with the usefulness of the if __name__ == "__main__" idiom, but it works just fine around the main code directly.

Jeff

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.