Reputation: 1472
The style guide says that underscores should be used, but many Python built-in functions do not. What should the criteria be for underscores? I would like to stay consistent with Python style guidelines but this area seems a little vague. Is there a good rule of thumb, is it based on my own judgment, or does it just not really matter either way?
For example, should I name my function isfoo()
to match older functions, or should I name it is_foo()
to match the style guideline?
Upvotes: 13
Views: 2126
Reputation: 141760
The style guide says that underscores should be used, but many Python built-in functions do not.
Using the built-in isinstance()
as an example, this was written in 1997.
PEP 8 -- Style Guide for Python Code wasn't published until 2001, which may account for this discrepancy.
What should the criteria be for underscores? I would like to stay consistent with Python style guidelines but this area seems a little vague. Is there a good rule of thumb, is it based on my own judgment, or does it just not really matter either way?
"When in doubt, use your best judgment."
It's a style guide, not a law! Follow the guide where it is appropriate, bearing in mind the caveats (emphasis my own):
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.
Therefore...
For example, should I name my function
isfoo()
to match older functions, or should I name itis_foo()
to match the style guideline?
You should probably call it isfoo()
, to follow the convention of similar functions. It is readable. "Readability counts."
Upvotes: 3
Reputation: 309811
The style guide leaves this up to you:
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
In other words, if you feel like adding an underscore to your method name would make it easier to read -- by all means go ahead an throw one (or two!) in there. If you think that there are enough other similar cases in the standard library, then feel free to leave it out. There is no hard rule here (although others may disagree about that point). The only thing which I think is universally accepted is that you shouldn't use "CapWords" or "camelCase" for your methods. "CapWords" should be reserved for classes, and I'm not sure of any precedence for "camelCase" anywhere (though I could be wrong about that) ...
Upvotes: 5