On Wed, Mar 24, 2010 at 2:42 PM, Ingy dot Net <[email protected]> wrote:
> Thanks fellas,
>
> Those are fine ideas, but I guess what I was really hoping for was not so
> much help with that specific question, but some review of my newbie python
> module code.
>
> In many ways, Python is very straightforward, but in other aspects I spent
> hours looking for the right way to do something. Often times I wasn't sure I
> got it right. I did read PEP-0008 and an old OSCON talk called "Code Like a
> Pythonista". Still it would be great to have some old hands give it a quick
> look. It's not that much code.
Here are some small-scale things that stand out in a skim, in order as
I read through the file:
- There are no tests for this code! ;)
- Don't call modules.__reversed__; magic methods are magic for a
reason and should very rarely be called directly. You want the
reversed() built-in instead.
- "del"ing local variables at the end of a function doesn't do
anything; it just destroyed the local reference, which would've been
destroyed when the function returned anyway.
- Short-circuiting "and"/"or" tricks are dangerous – in Python, there
many false values (0, [], {}, "", etc.) that can trip you up. Instead,
use a proper if statement or the ternary syntax: "val1 if condition
else val2".
- Instead of asking a dictionary for a key and catching the KeyError
(four lines), consider my_dict.get(key, default_value) (one line).
- Square the comments about and/or short circuiting when both "and"
and "or" are involved.
I hope this is useful. :)
--
Gary
http://blog.extracheese.org