41

I'm a Rubyist learning Python and I'm wondering if there is a convention in Python along the lines of the following.

In Ruby, methods that return booleans are supposed to always end in a ?. For example,

def palindrome?(string)
  # some code that tests whether string is a palindrome
end

The only existing SO question I can find speaking to this does not provide a definitive answer.

1
  • 1
    Since ? is not allowed in Python function names, and since English is is restricted to (3rd person) singular present tense questions of being (as opposed to other verbs), I suggest we use a more general yes/no question marker from another language that doesn't suffer the same problems, such as Japanese "ka" suffix.
    – LarsH
    Sep 30, 2021 at 17:35

3 Answers 3

28

There is no standard naming convention specific to boolean-returning methods. However, PEP8 does have a guide for naming functions.

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Typically, people start a function with is (e.g. is_palindrome) to describe that a boolean value is returned.

2
  • 22
    It's strange that the makers of Python don't adhere to their own recommendation of using underscores to separate words...
    – Kawu
    Dec 30, 2018 at 14:23
  • 5
    @Kawu Not really strange. First version of Python was developed in the early 1990's and the conventions have been evolving since then. When you publish some API, you cannot just rename everything because "somebody had a great idea about new naming convention".
    – user7610
    Feb 11, 2022 at 17:16
21

I concur with @CarolChen on the principle of turning to PEP8, the Python Style Guide, for guidance. I will suggest however that "as necessary to improve readability" is in the eye of the beholder. For example, each of these functions are used in Python either as functions of the str object or as builtin functions. These are as fundamental as it gets in the Python ecosystem and are good examples of a usage style focused on returning a boolean state AND having easily readable function names.

str. methods

isalnum()
isalpha()
isdecimal()
isdigit()
isidentifier()
islower()
isnumeric()
isprintable()
isspace()
istitle()
isupper()

builtin functions:

isinstance()
issubclass()
5

You can define it like

def is_palindrome(variable):
    # your logic\
    # return True / False

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.