Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python boolean methods naming convention

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.

like image 493
jayqui Avatar asked Dec 27 '17 17:12

jayqui


People also ask

How do you name a boolean method?

The usual convention to name methods that return boolean is to prefix verbs such as 'is' or 'has' to the predicate as a question, or use the predicate as an assertion. For example, to check if a user is active, you would say user.

Should booleans start with is?

[Mandatory] Do not add 'is' as prefix while defining Boolean variable, since it may cause a serialization exception in some Java frameworks.


2 Answers

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() 
like image 124
E. Ducateme Avatar answered Sep 22 '22 17:09

E. Ducateme


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.

like image 23
Carol Chen Avatar answered Sep 19 '22 17:09

Carol Chen