views:

99

answers:

3

I am putting a bunch of related stuff into a class. The main purpose is to organize them into a namespace.

class Direction:

  north = 0
  east = 1
  south = 2
  west = 3

  @staticmethod
  def turn_right(d):
    return turn_to_the_right

  @staticmethod
  def turn_left(d):
    return turn_to_the_left



# defined a short alias because direction will be used a lot
D = Direction

d0 = D.north
d1 = D.turn_right(d)

There is not much object concept involved. In C++, I will be using the actual language keyword namespace. There is no such thing in Python. So I am trying to use class for this purpose.

Is this a good idea? Any pitfall with this approach?

I've just answer a related question yesterday. This question is asked in a different way. It is an actual decision I need to make for myself.

Static method vs module function in python - Stack Overflow

http://stackoverflow.com/questions/3570823/static-method-vs-module-function-in-python/3571114#3571114

+7  A: 

No. Stick it in a module instead.

Python doesn't have namespaces in the same way that C++ does, but modules serve a somewhat similar purpose (that is, grouping "like" classes and functions together, and giving them unique names to avoid clashes).

Edit
I saw the comment you posted to your question. To answer more explicitly, no, in Pythonic code it's not really correct to use a class to emulate a namespace. Modules are there to group related classes, functions, and variables -- use a module instead. A class represents a "thing" that has a behavior (methods) and data (instance variables) -- it's not just a collection of standalone functions and variables.

mipadi
Is there stronger justification for module? I can think of an option to do `from direction import *`. On the other hand, if there are only 4 constants "north, east, south, west", it seems an overkill to put them in their own module.
Wai Yip Tung
You should put them where they make sense, from an organizational standpoint. If they "go together" with an existing module, put them there (you could rename them to `DIRECTION_NORTH` or whatever). If not, put them in a separate module, if that makes sense.
mipadi
A: 

Yes, it's fine. You can even use property to make methods look like attributes.

If you have a big class, it might be neater to use a module

katrielalex
A: 

It depends on the situation; if you can stick a constant in the module and have it make sense, by all means do so, but putting them in the class can make their meaning more obvious, and allow similar constants to have more "abstraction": placing them in the ServerError class makes more sense than having them all prepended with SERVER_ERROR residing freely in the module.

Do what is most intuitive, but try to avoid namespace pollution.

Beau Martínez