Good code patterns in Python

Kirk Job-Sluder kirk at
Wed Jul 2 08:48:23 CEST 2003

Will Stuyvesant <hwlgw at> wrote:
> 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?  

My personal opinion is that it depends on context.  The first idiom
is more clear when you are dealing with some kind of a switch.  The 
second idiom works better if you have a default value that needs to be 
overridden in some cases.

> 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.

Of course, another alternative is to combine both approaches by setting
a default value:

#set default for some_value
some_value = []
if condition1:
    some_value = function1()
    some_value = function2()

And then if you really want to be safe the functions using
some_value should do reality checks as well.
def function3(some_value=[]):
    if len(some_value):
        do something
        do something else.

I think that an argument for the readability of if-else is that because
the logic is made more clear, it can be more effectively replaced.

> 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:
> makes code ugly :-)

The problem here is that ***creating a new object reference*** is not
only ugly, but its ambiguous as well.  (What kind of object, what is it 
used for?) If indeed some_name is an important variable in your program,
then provide a full description.

#some_value (string) is used to hold the widgit that will 
#be passed to a wadget and eventually passed
#to standard output.  

Kirk Job-Sluder

More information about the Python-list mailing list