Classes as namespaces?

K

kj

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)


Granted, this is not the "intended use" for classes, and therefore
could be viewed as a misuse ("that's what dictionaries are for",
etc.). But other than this somewhat academic objection[*], I really
can see no problem with using classes in this way.

And yet, I've come across online murky warnings against using
classes as "pseudo-namespaces". Is there some problem that I'm
not seeing with this technique?

~K

[*] My own subjective dislike for the widespread practice of using
triple quotes to comment out code is formally similar to this one
("the 'intended use' for triple-quoting is not to comment out code",
etc.). Here I find myself on the opposite side of the purist/pragmatic
divide. Hmmm.
 
H

Harishankar

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)


Granted, this is not the "intended use" for classes, and therefore could
be viewed as a misuse ("that's what dictionaries are for", etc.). But
other than this somewhat academic objection[*], I really can see no
problem with using classes in this way.

And yet, I've come across online murky warnings against using classes as
"pseudo-namespaces". Is there some problem that I'm not seeing with
this technique?

~K

[*] My own subjective dislike for the widespread practice of using
triple quotes to comment out code is formally similar to this one ("the
'intended use' for triple-quoting is not to comment out code", etc.).
Here I find myself on the opposite side of the purist/pragmatic divide.
Hmmm.

I myself am a humble beginner in many ways, but generally isn't that
(namespacing) achieved by using modules?

I don't find the need generally to assign namespace to local variables
and when there is a need for it, module level objects do the job.
 
P

Philip Semanchuk

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)


Granted, this is not the "intended use" for classes, and therefore
could be viewed as a misuse ("that's what dictionaries are for",
etc.). But other than this somewhat academic objection[*], I really
can see no problem with using classes in this way.

And yet, I've come across online murky warnings against using
classes as "pseudo-namespaces". Is there some problem that I'm
not seeing with this technique?

I hope it's not problematic; I use it all the time.

A few differences about the way I do it:
- I respect PEP 8 for the class name (CamelCaps)
- If the attributes are supposed to be constants, I capitalize the
attributes
- I often add NONE with a value of zero so that bool(MyClass.NONE)
will evaluate to False and everything else will be True

Here's an example from my code:

class Apodization(object):
""" Apodization constants """
# These constants are arbitrary and may change.
# However bool(NONE) is guaranteed to be False
NONE = 0
GAUSSIAN = 1
LORENTZIAN = 2



Cheers
Philip
 
J

Jon Clements

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)

Granted, this is not the "intended use" for classes, and therefore
could be viewed as a misuse ("that's what dictionaries are for",
etc.).  But other than this somewhat academic objection[*], I really
can see no problem with using classes in this way.

And yet, I've come across online murky warnings against using
classes as "pseudo-namespaces".  Is there some problem that I'm
not seeing with this technique?

~K

[*] My own subjective dislike for the widespread practice of using
triple quotes to comment out code is formally similar to this one
("the 'intended use' for triple-quoting is not to comment out code",
etc.).  Here I find myself on the opposite side of the purist/pragmatic
divide.  Hmmm.

Given this example, I would go for the module and CONSTANT_NAMING
approach.

But yes, even in the docs. you can use a class as a C type-of struct.

I stick to the convention of a class knows what it's doing,
what it's doing it on, and a module just happens to contain those
classes.

C++ std::algorithm for instance,
makes sense it's called std, ditto algorithm and has shed loads in it,
but would I create a class called algorithm (unlikely).

I would tend to view modules as "namespace". Rightly or wrongly, just
lets you make the right design choice.

Jon.
 
J

Jack Diederich

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)

Classes as namespaces are a valid use case (I do it all the time).
Python 3 has a small cleanup that makes classes even closer to module
namespaces; namely the concept of "unbound methods" goes away. In
3.x when you get a function from a class you get the function itself
and not an unbound function.

-Jack
 
J

Jean-Michel Pichavant

kj said:
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)


Granted, this is not the "intended use" for classes, and therefore
could be viewed as a misuse ("that's what dictionaries are for",
etc.). But other than this somewhat academic objection[*], I really
can see no problem with using classes in this way.
You cannot see the problem because there's no problem using classes as
namespaces.
And yet, I've come across online murky warnings against using
classes as "pseudo-namespaces". Is there some problem that I'm
not seeing with this technique?

~K
import this
[snip]
Namespaces are one honking great idea -- let's do more of those!

Modules and dictionaries are no more namespaces than classes. So any
container is potentially a namespace.

JM
 
K

kj

Thanks for all your comments.

I see that modules are arguably Python's standard way for implementing
namespaces. I guess I tend to avoid modules primarily because of
lingering mental trauma over incidents of insane/bizarro import
bugs in the past. (It's not rational, I know; it's like when one
develops an aversion for some previously liked food after a bout
of food poisoning with it.) Now I postpone creating a new Python
module until the pain of not doing so forces me beyond my phobia.
(Yes, you got that right, I'm a basket case.)
 
P

Philip Semanchuk

Thanks for all your comments.

I see that modules are arguably Python's standard way for implementing
namespaces. I guess I tend to avoid modules primarily because of
lingering mental trauma over incidents of insane/bizarro import
bugs in the past.

There can be good reasons (i.e. unrelated to trauma) not to use a one-
namespace-per-module rule.

For instance, The app I'm working on now has 43 classes defined in a
constants.py file. Each class is just a namespace for constants.
That's much more practical than 43 modules called foo_constants.py,
bar_constants.py, etc.

My Currency(type=CurrencyType.USD, value=decimal.Decimal(".02")),
Philip
 
L

Luis M. González

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...
 
S

Steven D'Aprano

What's the word on using "classes as namespaces"?
[...]
Namespaces are one honking great idea -- let's do more of those!



[*] My own subjective dislike for the widespread practice of using
triple quotes to comment out code is formally similar to this one ("the
'intended use' for triple-quoting is not to comment out code", etc.).

On the contrary. CPython deliberately strips bare strings (whether triple
quoted or not) out during compilation. This isn't an accident, it is
deliberate.

.... x = 1
.... y = 2
.... # comment
.... "a string"
.... z = 4
.... """ 2 0 LOAD_CONST 0 (1)
3 STORE_NAME 0 (x)

3 6 LOAD_CONST 1 (2)
9 STORE_NAME 1 (y)

6 12 LOAD_CONST 2 (4)
15 STORE_NAME 2 (z)
18 LOAD_CONST 3 (None)
21 RETURN_VALUE


Why should you not do this? First, it is implementation-specific: other
Pythons may not behave the same. Potentially they may compile in the
(potentially large) string, push it on the stack, then immediately pop it
off again. Older versions of CPython used to do that for non-strings.


Secondly, and FAR more importantly, leaving large amounts of commented
out code in your source is a TERRIBLE idea. Yes, sure, it's tempting to
do, especially for quick and dirty scripts. Resist the temptation. Learn
how to use a proper code repository. Don't leave the detritus of ancient
unused code in your source files -- it confuses the reader, makes
searching harder, slows down parsing, and (trust me) you will never need
to read the old code again. It just gets in the way.

Of course, like everything, this needs to be considered in context. You
might leave commented-out code like this:

# DON'T DO THIS:
# s = spam(s, s*2)
# It doesn't work. See bug #12345 in the tracker. Instead do this:
s = spam(s*2, s)
 
J

Jonathan Hartley

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?
 
J

J. Clifford Dyer

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?

Hmm. I don't like that because it leaves a class polluting your namespace that doesn't behave like a class. Using a function for that purpose doesn't seem as bad, because even if you don't call it again, at least you *could*, and it would behave in an expected fashion.

If you're dead-set against calling the chunk of code you just created, and you're using python 2.5 or higher, you might consider creating a no-op context manager:

x = 1
with code_block("Account for non square pixels"):
((complex_logic))
y = 2

Though in general, I think refactoring your code to reasonably scoped functions or methods is a better idea. If it's too complex to read in one block, it's probably too complex for one function.
 
J

Jean-Michel Pichavant

Jonathan said:
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
 
J

J. Clifford Dyer

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)


Granted, this is not the "intended use" for classes, and therefore
could be viewed as a misuse ("that's what dictionaries are for",
etc.). But other than this somewhat academic objection[*], I really
can see no problem with using classes in this way.

And yet, I've come across online murky warnings against using
classes as "pseudo-namespaces". Is there some problem that I'm
not seeing with this technique?

~K

I don't see anything wrong with this, except that I would clean it up in a couple ways. Like other posters, I would give the class a proper class name (Cfg).

I also would not assign integers to spam, jambon, or huevos. Instead I would assign each a bare object(). That way you won't get unexpected interactions with other constants outside the class. An object() is equal only to itself.

I would also not rule out letting your "pseudo-namespace" grow into a full-fledged class. If you've got a method that makes sense with your class, use it.

class Cfg(object):
spam = object()
jambon = object()
huevos = object()

def get_animal(self, meat):
if meat == self.jambon:
return 'pig'
elif meat == self.huevos:
return 'chicken'
elif meat = self.spam:
return 'spamalope'

Later, perhaps, you might refactor so that each meat type (OK so huevos aren't a meat) gets its own subclass, with a simple, one-line get_animal method.

Cheers,
Cliff
 
S

Steve Holden

J. Clifford Dyer said:
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 also would not assign integers to spam, jambon, or huevos. Instead
I would assign each a bare object(). That way you won't get
unexpected interactions with other constants outside the class. An
object() is equal only to itself.
It also has the advantage (?) that you can use "is" (identity)
comparisons rather than testing for equality, though this is only a
readability issue, I suspect.

regards
Steve
 
P

Philip Semanchuk

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)


Granted, this is not the "intended use" for classes, and therefore
could be viewed as a misuse ("that's what dictionaries are for",
etc.). But other than this somewhat academic objection[*], I really
can see no problem with using classes in this way.

And yet, I've come across online murky warnings against using
classes as "pseudo-namespaces". Is there some problem that I'm
not seeing with this technique?

~K

I don't see anything wrong with this, except that I would clean it
up in a couple ways. Like other posters, I would give the class a
proper class name (Cfg).

I also would not assign integers to spam, jambon, or huevos.
Instead I would assign each a bare object(). That way you won't get
unexpected interactions with other constants outside the class. An
object() is equal only to itself.

What I like about this method is that it will break the bad habit I
see in junior programmers of making assumptions about the value of the
constant. For instance, if they see that Cfg.JAMBON = 3 and hardcode 3
in their code somewhere, that will work fine until someone re-orders
the constants. Using object() instead forces them to use Cfg.JAMBON
since the value will (probably) change with every run of the program.

It will also discourage bugs-waiting-to-happen like this:
if breakfast > Cfg.SPAM:
print "Good news, breakfast is jambon or huevos"



bye
P
 
E

Ethan Furman

Jonathan said:
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?

Both solutions look horrible to me, as both hurt readability. Make your
function somewhere else, then call it in the code. Who cares if you
only use it once?

x = 1
account_for_non_square_pixels()
y = 2

Isn't that easier to read?

And when you want to (read/change) the complex code, you have an easy
place to go to do it.

~Ethan~
 
T

Terry Reedy

On Mar 26, 6:26 pm, Luis M. González<[email protected]> wrote:
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?

The assignments within the class are performed within a new local
namespace. So moving non-toy code within a class block will typically fail.
 
P

Patrick Maupin

The assignments within the class are performed within
a new local namespace.

I could be misunderstanding, but I think that may be the point. When
you have what is basically a bunch of linear logic in Python,
sometimes it makes sense to break the logic up into separate
namespaces, such that you don't pollute the global namespace too badly
(which could cause obscure failures due to inadvertently reusing a
variable name which is not properly initialized on the second use).

As the OP mentioned, functions are typically used for this, but then
you have to decide if you are going to put all your functions above
all the rest of the code, or in-line, which is where they belong
according to the flow. Either decision has drawbacks -- it is jarring
to see functions defined in the middle of a code flow, but it requires
extra work to page up and down to see code that is logically in the
middle of a code flow, but has been moved out to a sub-function
somewhere.
So moving non-toy code within a class block
will typically fail.

I think, as with moving non-toy code into a function, the point may be
to *force* (more obvious) failures when something is screwed up,
rather than allowing the silent failures that can easily occur with a
large number of only marginally related variables in one big
namespace.

I have done what (I think) the OP is suggesting in the distant past.
I don't know why I don't do it any more -- perhaps it is more of a
comfort thing, or maybe I have gotten better at choosing the right
abstraction points for the function boundaries so that I don't always
need to read the function code when I am reading the code that invokes
it. But in any case, I don't personally think that:

a = 27
b = 30

class DoMoreComputation:
c = a + b

d = DoMoreComputation.c

is a terrible, ugly thing, although it is not my current preference.

Regards,
Pat
 
G

Gregory Ewing

Jonathan said:
def account_for_non_square_pixels(x):
((some complex logic))
account_for_non_square_pixels()
class account_for_non_square_pixels:
((some complex logic))

I don't see much advantage -- you're still leaving behind an
object that won't be used again.

If you're concerned about namespace pollution, there are a
couple of ways to clean it up:

1) Delete the function after using it:

def account_for_non_square_pixels(x):
...
account_for_non_square_pixels()
del account_for_non_square_pixels

2) Use __all__ to specify which names you intend to export
(doesn't prevent anyone from importing something explicitly,
but at least it makes your intention clear, stops irrelevant
things appearing in dir() or help(), etc).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top