I'm confused about choosing names for my functions in Python. Sometimes Python built-in functions are imperative such as: print
function and string method find
. Sometimes they aren't such as: len
its name isn't imperative such as calculate_len
, for instance, and type
isn't find_type
.
I can understand that print
returns a value that we don't use (i.e None
) and does something (i.e it shows a string on the screen), so its name is imperative.
But len
returns a value that we use and does something (i.e. calculating how many items there are in a sequence or a mapping.) and its name isn't imperative. On the other hand, find
string method (as len
) returns a value that we use and does something, and its name is imperative.
What made ask this question is that I put a script that encrypt and decrypt string using Caesar cipher to being reviewed. The reviewer said that:
Just a gut feeling: functions do stuff. So a good name for a function is an imperative: I'd use
rotate_letter
instead ofrotated_letter
.
rotated_letter
returns a single-letter string representing a letter rotated by a number. I don't know what is better, I used rotated_letter
as it returns a value, like randint
function in random module, it isn't generate_randint
.
So, in this case, how should I name a function that returns a value to be used? Should I make the name imperative or just a noun. In other cases it's obvious how to do it, such as boolean functions, such as is_even
and is_palindrome
we just make it like a yes/no question, and also functions that just do and return non-used values (i.e None
), such as print
and list method sort
.
len
, for example, is better thought of as "length of" - you're getting a meta-level description of its argument.