Style for modules with lots of constants

Rob Williscroft rtw at freenet.co.uk
Wed Nov 1 15:52:40 EST 2006


Tim Chase wrote in news:mailman.1617.1162412498.11739.python-
list at python.org in comp.lang.python:

>>> 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,
>> 
>> Sorry I don't know what you mean here, could I have an example
> 
> 
> It helps in the recognition if you have separation between 
> something like
> 
>      turnDirection.LEFT

class turnDirection( object ) : pass
turnDirection.LEFT = 0
turnDirection.RIGHT = 1

> 
> and
> 
>      alignment.LEFT

class alignment( object ) : pass
alignment.LEFT = 3

> 
> They may be the same or different value for LEFT, but by grouping 
> them in a "descriptive context", it's easy to catch mistakes such as
> 
>      paragraph.align(turnDirection.LEFT)
> 
> when what you want is
> 
>      paragraph.align(alignment.LEFT)
> 
> and, as an added bonus, prevents name clashes such as
> 
>      turnDirection.LEFT = 2
>      alignment.LEFT = 0
>
> With the grab-bag o' constants, you have to use old-school 
> C-style in your modern name-space'd Python:
> 
>      gboc.TURN_LEFT = 2
>      gboc.ALIGN_LEFT = 0
> 
> or even worse, you'd end up with cruftage where you have
> 
>      gboc.LEFT = 2
>      gboc.ALIGN_LEFT = 0 #created a month later as needed
> 
> and then accidentally call
> 
>      paragraph.align(gboc.LEFT)
> 
> when you mean
> 
>      paragraph.align(gboc.ALIGN_LEFT)
> 
> This is what I understand the grandparent's post to be referring 
> to by "descriptive context".

Fair enough, but there is nothing in this that can't be done with
pure (instance free) classes as shown above, with the advantage
that the client just imports the name for the set of constants 
they want to use, and uses them with no need to construct.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/



More information about the Python-list mailing list