Domanda

In Python code, what is the canonical way of dealing with well-known acronyms when naming classes, methods and variables?

Consider, for example, a class dealing with RSS feeds. Would that rather be this:

class RSSClassOne:
    def RSSMethod(self):
        self.RSS_variable = True

class ClassRSSTwo:
    def MethodRSS(self):
        self.variable_RSS = True

or this:

class RssClassOne:
    def rssMethod(self):
        self.rss_variable = True

class ClassRssTwo:
    def MethodRss(self):
        self.variable_rss = True

I.e. what is more important, keeping the acronym capitalization or the recommendations of PEP 008?

Edit: from the answers, I conclude that this would be the way to go:

class RSSClassOne:
    def rss_method(self):
        self.rss_variable = True

class ClassRSSTwo:
    def method_rss(self):
        self.variable_rss = True
È stato utile?

Soluzione

Well, it turns out that PEP 8 already has this topic covered here:

Note: When using abbreviations in CapWords, capitalize all the letters of the abbreviation. Thus HTTPServerError is better than HttpServerError.

In other words, the Python convention for names containing acronyms is:

  1. Keep acronyms uppercase in class names (usually, the only part of Python that uses CapWords).

  2. Everywhere else, make them lowercase in order to comply with the other naming conventions.

Below is a demonstration with the ipaddress module:

>>> import ipaddress  # IP is lowercase because this is a module
>>> ipaddress.IPv4Address  # IP is uppercase because this is a class
<class 'ipaddress.IPv4Address'>
>>> ipaddress.ip_network  # IP is lowercase because this is a function
<function ip_network at 0x0242C468>
>>>

Altri suggerimenti

I don't think that there is anything wrong with the first one at all. As an acronym represents a series of words and in Python class names you do CamelCase at the start of each word, it is perfectly OK to capitalise each letter (word) in the acronym.

The first code example, therefore conforms to the style guide for Python code probably more than the second. In short, the first one because PEP8 conformation is extremely important. :)

Bear in mind also that there are sometimes (albeit very rarely) instances in which these rules can be bent slightly. This could be considered one of them.

I would say that following the recommendation in PEP 8 is the first thing to do related to coding style.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top