Is it a good idea to using class as a namespace in Python

Viewed 10034

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

Static method vs module function in python

6 Answers

I mostly agree with @uchuga's answer, but I want to emphasize a caveat:

a = "global"
class C:
    a = "class"
    def f():
        print(a)
    f()

... will print "global", not "class".

In my opinion, a class is a class, and a Namespace is a namespace. You can use argparse.Namespace like so to create a namespace:

from argparse import Namespace

directions = Namespace(
    north = 0,
    east  = 1,
    south = 2,
    west  = 3,
)

print(directions.north)  # 0
print(directions.east)   # 1
print(directions.south)  # 2
print(directions.west)   # 3
Related