Style for modules with lots of constants

Paul McGuire ptmcg at austin.rr._bogus_.com
Wed Nov 1 18:27:06 CET 2006


"Rob Williscroft" <rtw at freenet.co.uk> wrote in message 
news:Xns986EAF9E3447DrtwfreenetREMOVEcouk at 216.196.109.145...
> Paul McGuire wrote in news:XU32h.436$lx6.417 at tornado.texas.rr.com in
> comp.lang.python:
>
>>
>> class Constants(object)
>>     pass
>>
>> (I guess value immutability could probably be implemented using clever
>> implementations of __setattr__ and such, but is it really worth the
>> bother?).
>>
>> Then I defined the context for my LEFT and RIGHT constants, which are
>> being created to specify operator associativity, and then my constant
>> fields as attributes of that object:
>>
>> opAssoc = Constants(object)
>> opAssoc.RIGHT = 0
>> opAssoc.LEFT = 1
>>
>
> This is nice, but you can cut down on some of the cruft:
>
> class Constants( object ):
>  pass
>
> Constants.RIGHT = 0
> Constants.LEFT = 1
>
> ## client code ...
> print Constants.LEFT
>
> Rob.

One man's cruft is another man's clarity.  The reason I used instances 
instead of just the Constants class was so that I could define a little more 
descriptive context for the constants, rather than simply a shortcut for 
importing lots and lots of constant definitions.  I expect I will want to 
define some more constants for other parts of pyparsing, and the instance 
scoping helps organize them, that's all.  It's really a style/taste issue at 
this point.  What you've written will certainly work, and if Neil has many 
constants in his module, what you suggest would be a way to import them all 
at once.

-- Paul





More information about the Python-list mailing list