When should underscores be used between words in Python function names (as per the style guide)?

the style guide says underscores should be used, but many Python built-in functions don't. What should be the criteria for underlining? I would like to adhere to the principles of the Python style, but this area seems a bit vague. Is there a good rule of thumb, is it based on my own judgment, or does it just not matter anyway?

For example, should I specify my isfoo() function to match old functions, or should I call it is_foo() according to the style directive?

+6
source share
2 answers

The style guide leaves this for you:

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

In other words, if it seems to you that adding an underscore to the name of your method would make it easier to read, by all means you can drop one (or two!) There. If you think that the standard library has enough other similar cases, then feel free to leave it. There is no hard rule (although others may disagree with this point). The only thing that I consider generally accepted is that you should not use "CapWords" or "camelCase" for your methods. "CapWords" should be reserved for classes, and I'm not sure of any priority for "camelCase" anywhere (although I could be wrong about that) ...

+4
source

The style guide says underscores should be used, but many Python built-in functions don't.

Using the built-in isinstance() as an example, this was written in 1997 .

PEP 8 - The Style Guide for Python Code was not published until 2001 , which may explain this discrepancy.

What should be the criteria for underlining? I would like to adhere to the principles of the Python style, but this area seems a bit vague. Is there a good rule of thumb, is it based on my own judgment, or does it just not matter anyway?

"If in doubt, use your best solution."

This is a style guide, not a law! Follow the manual where appropriate, given the caveats (highlighting my own):

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

mixedCase is only allowed in contexts where style is already prevailing (e.g. threading.py), in order to maintain backward compatibility .

Therefore...

For example, should I specify my isfoo() function to match old functions, or should I call it is_foo() according to the style directive?

You should probably call it isfoo() to follow the convention of similar functions. It is readable. "Reading is calculated."

+1
source

All Articles