Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant class attribute style according to PEP8: uppercase or lowercase?

I really like to follow the standard coding style, but can't find an answer on this.

class Card:
    """Card class representing a playing card."""
    RANKS = (None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10',
             'Jack', 'Queen', 'King')
    SUITS = ('Clubs', 'Spades', 'Diamonds', 'Hearts')

    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        return f"{Card.RANKS[self.rank]} of {Card.SUITS[self.suit]}"


c = Card(1, 1)
print(c)

Should I write constants in class attributes all_lower_case or ALL_UPPER_CASE? PEP8 just says that constants should be ALL_UPPER_CASE at the module level. What about classes?

like image 330
rrebase Avatar asked Aug 15 '17 22:08

rrebase


People also ask

Should constants be capitalized?

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

Should constants be capitalized in Python?

In Python, constants are usually declared and assigned in a module. Here, the module is a new file containing variables, functions, etc which is imported to the main file. Inside the module, constants are written in all capital letters and underscores separating the words.

Should class variables be capitalized Python?

In proper python code, your class name should be capitalized. This helps to differentiate a class from a normal variable or function name.

What are uppercase variables in Python?

Variables can only contain upper and lowercase letters (Python is case-sensitive) and _ (the underscore character). Hence, because we can't have spaces in variable names a common convention is to capitalize the first letter of every word after the first. For example, myName, or debtAmountWithInterest.


2 Answers

PEP8 makes it clear that constants should be upper-case:

Constants

Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.

Note that it just says that these are usually defined on a module level. But if your values should be treated as constants then make them uppercase - even if they are defined on a class level.

like image 165
MSeifert Avatar answered Oct 13 '22 11:10

MSeifert


Why not extract those outside of the class in the module like this:

from enum import Enum

class Suit(Enum):
    CLUBS = 1
    SPADES = 2
    DIAMONDS = 3
    HEARTS = 4

Then you could use it like:

Card(Rank.1, Suit.SPADES)

Also according to the following Python documentation it's ALL_CAPS, even inside Class. This also makes sense to me.

More info and examples.

like image 25
Maiku Mori Avatar answered Oct 13 '22 09:10

Maiku Mori