Good code patterns in Python

Will Stuyvesant hwlgw at hotmail.com
Tue Jul 1 11:49:54 CEST 2003


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

Why?  

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.

There is the small overhead of assigning something twice
to some_name in the safer example, so if performance is
*that* important then the first example is better, but I
feel there should be comments with warnings around it:
**CREATING A NEW OBJECT REFERENCE HERE!** Hmm, now that
makes code ugly :-)

What are your thoughts about this?  I am interested in
current large scale software development practice, and
guidelines that are used there, especially for dynamically
typed languages like Python.

There must be a lot of advisable code design patterns (I
can't find a good name in English) like this for use in
software development with many programmers.  Perhaps a
collection with good documentation would be interesting?
Or a tool like pychecker that flags "bad" patterns?


-- 
People who miss goto now use exceptions




More information about the Python-list mailing list