Good code patterns in Python

Steven Taschuk staschuk at telusplanet.net
Tue Jul 1 14:26:35 EDT 2003


Quoth Will Stuyvesant:
> If you know that your source code is going to be used
> later by others, then I feel that code with the pattern:
> 
>     if some_condition:
>         some_name = some_value
>     else:
>         some_name = other_value
> 
> is often a mistake.  Much better, safer, would be:
> 
>     some_name = some_value
>     if not some_condition:
>         some_name = other_value

I join the Ms in disagreeing strongly.  The visual parallelism of
the first reflects the conceptual parallelism of the two cases,
while the second obscures it.

> Because those people reusing your code might decide to
> change or adapt the "if" part of the first example.  Or
> the "else" part for that matter.  And then they could end
> up with "some_name" being undefined, crashing other code
> maybe 1000's of lines away.  This could happen for example
> because they use exceptions in the "if" part that jump out
> of it, etc.

I assume you're not speaking of local variables here -- a function
thousands of lines long would be unconscionable.

Presumably you're speaking of attributes, and the danger is that
an exception in one branch would cause the object's invariants be
broken.  But I don't see how this would happen in practice, in a
way which would (a) leave the attribute undefined and (b) imply to
the caller that everything was fine.  Do you have an example?

(Much more serious and more common is the danger that after an
exception is raised, the function has done half its work and left
the object in a broken state.  But this has nothing to do with
what you're talking about.)

> There is the small overhead of assigning something twice

Too minor to worry about:

    $ timeit -s'def foo(): global a; a = 1' 'foo()'
    100000 loops, best of 3: 5.51 usec per loop
    $ timeit -s'def foo(): global a; a = 1; a = 1' 'foo()'
    100000 loops, best of 3: 6.1 usec per loop

If I'm running the code a million times, and everything else in
the loop takes less than a microsecond, this might be worth
thinking about.

-- 
Steven Taschuk                                                   w_w
staschuk at telusplanet.net                                      ,-= U
                                                               1 1





More information about the Python-list mailing list