[Baypiggies] Discussion for newbies/beginner night talks

Shannon -jj Behrens jjinux at gmail.com
Sat Feb 10 00:55:16 CET 2007


On 2/9/07, Alex Martelli <aleax at google.com> wrote:
> On 2/9/07, Chad Netzer <chad.netzer at gmail.com> wrote:
>    ...
> > Some Python beginner tips and idioms:
> >
> > 1) Do not use lists, dicts, or any mutable object as default
> > arguments; use None instead.
> >
> > 2) If you need to do a lot of string appends, use lists and join().
> >
> > 3) Understand and use iterators in loops.
> >
> > 4) Use dictionaries, sets, and other mappings for searches and
> > queries.
> >
> > 5) Understand and use the decorate/sort/undecorate (DSU) idiom.
>
> ...which is best expressed today with the key=... argument to sort &c.
>
>
> > 6) Catch exceptions that you can handle, don't suppress ones you
> > can't.
> >
> > 7) Ask forgiveness, not permission. Ie. perform conversions and
> > other operations using "try". Avoid queries to determine if an
> > operation will succeed.
> >
> > 8) Use assert() to document your code.
> >
> > 9) Don't overuse tuples as "read only" lists.  Use them to make
> > dictionary keys, or pass around short lived groups of objects.
> >
> > 10) Use open() to open files, not file(). (trivial, perhaps)
>
> 11) never, ever alter the list (or other mutable container) on which
> you're looping with a 'for' statement -- when feasible, build a new
> container -- or, if you must, loop on a copy of the original container
> if you absolutely do need to alter the original
>
> 12) if you think you need to use 'eval', or, even worse, 'exec', think
> again -- most likely you do NOT need it (read up about getattr and
> setattr builtins); if you DO need it, it's almost unheard of that
> you'll need to do it with default locals and globals -- almost
> invariably, for the rare cases where eval (or exec... if ever...) is
> appropriate, you want one or two explicit dictionaries for locals and
> globals.
>
> 13) eschew eschew repetition repetition -- say what you mean and say it ONCE

Agreed.  The beauty of Python is looking at two chunks of code that
look the same but couldn't easily be refactored into a single block of
code in C (without macros).  In Python, thanks to meta programming, if
text "looks" similar, you can usually factor out the similarity.

-jj

-- 
http://jjinux.blogspot.com/


More information about the Baypiggies mailing list