def predicate_p

January 19, 2008

A very common Ruby idiom involves writing boolean-valued functions with question marks at the end. It felt sort of unusual at first, but I found it made for very clear and concise code. I recently found myself wanting to do this in Python but unfortunately it’s not possible in most other languages because function names cannot contain the ? character.

In Ruby, one would write something like this:

def authorized?
    # Determine if the user is authorized
end

def check_authorization
    if not authorized?
        # Redirect to the login page
    end
end

I wanted to adapt the same idiom to Python so I tried to find out what other people were doing. In a message sent to python-list, Harry George suggested using a _p suffix in keeping with Common Lisp’s -p form.

It turns out that the p is for “predicate”. In English, the predicate of a sentence is the part that modifies the subject. Linguistically speaking, a predicate is an expression that can potentially be true of something. For example, the phrase “is authorized” is true of objects that are authorized to access something.

The aforementioned Ruby and Lisp idioms show that this concept translates to code very easily. Like predicates in language an object’s boolean-valued members can either be true or false. In Python the above translates to def authorized_p and if not authorized_p. I think this is a good convention to follow in Python—I only wish the mnemonic were more obvious to someone first encountering it.