Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should class-specific "constants" still be declared at module level?

In PEP 8, it's stated that "Constants are usually defined on a module level […]". This makes sense for the standard library, where constants tend to pertain to the entire module rather than a particular class (e.g. zlib.MAX_WBITS or re.UNICODE). I'm currently writing a module, however, where the constants are all related to individual classes.

The module is designed to allow Python programs to work with an application-specific serialization format in which blocks of data are arranged into "chunks" and those chunks are further arranged into "regions". The dimensions of chunks and regions are useful constants to expose, and I had been doing so as class properties until I chanced across that line in PEP 8.

I'm inclined to leave them as they are (PEP 8 also says "foolish consistency is the hobgoblin of little minds", after all), but want to make sure that I won't be too badly breaking users' expectations by doing so. (The module hasn't yet been released, so backwards compatibility isn't an issue.)

For reference, "PEP 8" style…

CHUNK_SIZE_X = 16
CHUNK_SIZE_Z = 16
REGION_SIZE_X = 32
REGION_SIZE_Z = 32

def Chunk(object):
    # magic happens here

def Region(object):
    # magic happens here

…and my current, "class-based" style…

def Chunk(object):
    SIZE_X = 16
    SIZE_Z = 16

    # magic happens here

def Region(object):
    SIZE_X = 32
    SIZE_Z = 32

    # magic happens here
like image 227
Ben Blank Avatar asked Feb 23 '11 19:02

Ben Blank


People also ask

Where should constants go 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.

Where do you put class constants?

A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.


1 Answers

Clearly, class-based constants belong in the class. Stick with your second example. Remember PEP8 is not handed down from the Almighty. It's just good ideas: tradition, reason and experience can temper the meaning of scripture.

Hungrarian_prefix_notation is needless. That's one reason you have classes.

like image 110
S.Lott Avatar answered Oct 19 '22 22:10

S.Lott