Tips for readable python code

March 2nd, 2010

In this post I will try to explain some tricks I use to make python code more readable. These tips won’t make your code shorter and it won’t be better optimized, it will actually use more memory than before, but it will be much easier to understand and edit for someone else.

Using descriptive names

Ok, this is quite obvious but I will write it anyway. You should avoid using names like “var24″ , “cpnow(x)”, “move” and similar.

Old code

x = usr.id
add(x)
show(x)
New code

current_user_id = User.id
add_user_to_admins(x)
show_user_data(x)

Proximity

Proximity is often used in graphical design, if text is grouped together we assume it is related. Be sure to use this. Here is an example of good use of proximity.

marketing_data.compute_quarterly()
marketing_data.compute_annual()
marketing_data.print_data()
 
visitors_data.compute_quarterly()
visitors_data.compute_annual()
visitors_data.print_data()
 
sales_data.compute_quarterly()
sales_data.compute_annual()
sales_data.print_data()

Avoiding magic numbers

All literal numeric values except 0 and 1 should be avoided. Instead you could use a variable with a descriptive name. This way code will be more readable and it will be easier to change later.
Here is one trivial example.

Old code

x = 0
 
for x in range(5):
    print "\n"
New code

x = 0
SKIP_LINES = 5
 
for x in range(SKIP_LINES):
    print "\n"

This may seem unnecessary, but imagine a lot longer code with multiple occurrences of skip lines constant. This way you will avoid editing that number more than once if your code needs to be changed, and it’s much easier to understand a piece of code if variables with descriptive names are used.

Logical expressions

You can avoid writing big, multiple lines logical expressions by using boolean variables. Be sure to give descriptive names to those variables. Here is an example of how not to do it.

if  ( post.length > minimum_post_length and post.length < maximum_post_length and
    post.number_of_comments == 0 ):
    do_something()
else: do_something_else()

Now try to read if statement again, isn’t this better? And we really didn’t use much more memory.

post_is_longer_than_minimum = post.length > minimum_post_length
post_is_shorter_than_maximum = post.length < maximum_post_length
post_has_no_comments = post.number_of_comments == 0
 
if post_is_longer_than_minimum and post_is_shorter_than_maximum and post_has_no_comments:
    do_something()
else: do_something_else()

Using multiple if branchings properly

You should always put more common (or normal) cases first, and less common cases and exceptions later. This way normal program flow will be obvious.

current_user = get_user()
 
if not current_user:
    show_error()
else:
 
    if user_is_admin:
        show_admin_interface()
 
    else:
        show_normal_interface()

You should first handle case when there was no errors when trying to get user. And assuming there are lot more normal users than admins you should check if user isn’t admin first.

current_user = get_user()
 
if CurrentUser:
 
    if not user_is_admin:
        show_normal_interface()
 
    else:
        show_admin_interface()
 
else:
    show_error()

Conclusion

So, that’s it! If you have any more ideas, or know better methods of cleaning python code feel free to comment.

  • Java Jeeves
    People say that Python is an extremely readable language, yet I fail to see how it is any more readable. This article is a case in point, since every suggestion you've made is to do with the coder's choice of variable names - and the same can be applied to any other programming language.

    I don't mean to sound big-headed, but I just think Python, though a good language, is overly praised which is part of the reason I'm not too fond of it.
  • just wondering
    in python, is this preferred?

    if (minimum_post_length < post_length < maximum_post_length):
    do_something()
  • What's with the JavaStyleNames? Ugly and not very readable. Dude, PEP 8 is the_pythonic_way.
  • dabrorius
    thanks :) fixed
blog comments powered by Disqus