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
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.
Who consumes the constant? You say "I'm currently writing a module, however, where the constants are all related to individual classes." So put the constant in the class.
精彩评论