Classes as namespaces?

Jean-Michel Pichavant jeanmichel at sequans.com
Sat Mar 27 07:54:42 EDT 2010


Jonathan Hartley wrote:
> On Mar 26, 6:26 pm, Luis M. González <luis... at gmail.com> wrote:
>   
>> On 26 mar, 11:49, kj <no.em... at please.post> wrote:
>>
>>     
>>> What's the word on using "classes as namespaces"?  E.g.
>>>       
>>> class _cfg(object):
>>>     spam = 1
>>>     jambon = 3
>>>     huevos = 2
>>>       
>>> breakfast = (_cfg.spam, _cfg.jambon, _cfg.huevos)
>>>       
>> I see no problem.
>> I wouldn't mix English, French and Spanish in the same recipe though...
>>     
>
>
> Hey everyone. By coincidence, only yesterday I was wondering about
> using classes as a way of labeling a block of code, ie. an lightweight
> alternative to defining a function that would only be called from one
> location.
>
> eg. instead of:
>
>
> x = 1
> ((some complex logic))
> y = 2
>
>
> one might like to name the complex block of logic, just to make it
> readable:
>
>
> x = 1
> def account_for_non_square_pixels(x):
>    ((some complex logic))
> account_for_non_square_pixels()
> y = 2
>
>
> But defining and then calling the function like that is a tad
> cumbersome. So I was wondering about:
>
>
>
> x = 1
> class account_for_non_square_pixels:
>   ((some complex logic))
> y = 2
>
>
> I don't exactly like this, but I think you can see what I'm getting
> at. Does this fall down in some way I haven't grasped? Is it as awful
> an abuse of 'class' as my intuition suggests it is? Is there a way to
> do it better?
>   
on good way to label part of the code is to simply add comments. You can 
also find tricks to indent this code block, but I've never seen that before.

x=1
# account for non square pixels
some complex logic
# done
y=2

I'm perfectly comfortable using classes for namespaces, 'cause classes 
implement objects or entities, and a namespaces can easily be designed 
as a coherent entity.
For labelling code that you will not reuse, I'm not sure classes are 
suitable in the way people may issue a 'WTF' when reading your code.

JM



More information about the Python-list mailing list