Salvatore Lopiparo

Software Engineer

Super Simple Python – Function and Variable Names

One of the best ways to keep your code clean and understandable is to use well defined function and variable names. Take, for example, the following bit of code:

def get_stuff(p, dirs=False):
    return_list = []
    for a, b, c in os.path.walk(p):
        return_list.extend(c)
        if dirs:
            return_list.extend(b)
    return return_list

It takes a lot of effort to figure out what is going on here. We can tell from the function name get_stuff that it’s used to get something, but what is it getting? The arguements p and dirs are very ambiguous. The p argument says nothing about what it is, and the dirs argument implies that it is a list of directories, but it’s actually a boolean! The a, b, and c variables have completely useless names. At least return_list tells us that it’s intended to be returned… though a good comment can do that much clearer!

Here’s the same function re-written with much more understandable function and variable names.

def get_file_names(path, include_directories=False):
    """
    Gets a list of all file names in the given path, including files in subdirectories.
    """
    list_of_file_names = []
    for root, dirs, file_names in os.path.walk(path):
        list_of_file_names.extend(file_names)
        if include_directories:
            list_of_file_names.extend(dirs)
    return list_of_file_names

For those people who are worried about the extra time they’re saving by using short names, think again! If you find a bug in the code or need to modify it in the future, trying to decipher the cryptic function will more than make up the difference in time. In addition, all modern IDEs (and even some text editors) have code completion, letting you only need to type a couple letters to fill out an entire variable name.