Evaluate my first python script, please

sjdevnull at yahoo.com sjdevnull at yahoo.com
Fri Mar 5 19:19:37 CET 2010


On Mar 5, 10:53 am, Pete Emerson <pemer... at gmail.com> wrote:
> Thanks for your response, further questions inline.
>
> On Mar 4, 11:07 am, Tim Wintle <tim.win... at teamrubber.com> wrote:
>
> > On Thu, 2010-03-04 at 10:39 -0800, Pete Emerson wrote:
> > > I am looking for advice along the lines of "an easier way to do this"
> > > or "a more python way" (I'm sure that's asking for trouble!) or
> > > "people commonly do this instead" or "here's a slick trick" or "oh,
> > > interesting, here's my version to do the same thing".
>
> > (1) I would wrap it all in a function
>
> > def main():
> >     # your code here
>
> > if __name__ == "__main__":
> >     main()
>
> Is this purely aesthetic reasons, or will I appreciate this when I
> write my own modules, or something else?

Suppose the above code is in mymodule.py.  By wrapping main() you can:
1. Have another module do:
import mymodule
... (so some stuff, perhaps munge sys.argv)
mymodule.main()
2. If mymodule has a small function in it, someone else can import it
and call that function
3. You can run pylint, pychecker and other source-code checkers that
need to be able to import your module to check it (I wouldn't be
surprised if recent versions of one or the other of those don't
require imports, and some checkers like pyflakes certainly don't).
4. You can easily have a unit tester call into the module

etc.

> > (2) PEP8 (python style guidelines) suggests one import per line
>
> > (3) I'd use four spaces as tab width

+1 on both; it's good to get into the habit of writing standard-
looking Python code.



More information about the Python-list mailing list