Vulpes Vulpes -3 years ago 154
Python Question

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download