Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper use of class constants in Python

This question specifically relates to the use of the class constants ABOVE and BELOW in the sample code below.

I have a few different classes in different modules that look like this:

class MyClass(object):
    ABOVE = 1
    BELOW = 0

    def __init__(self):
        self.my_numbers = [1,2,3,4,5]

    def find_thing_in_direction(self, direction, cutoff):
        if direction == self.ABOVE:
            return [n for n in self.my_numbers if n > cutoff]
        else:
            return [n for n in self.my_numbers if n < cutoff]


my_class = MyClass()
my_var = my_class.find_thing_in_direction(MyClass.ABOVE, 3)

If I have a handful of classes scattered across different modules that each have their own ABOVE and BELOW, should I extract these constants to somewhere, or is it better to keep the constants within their own classes?

Is there a more Pythonic way to do this instead of using these class constants?

like image 652
Thomas Johnson Avatar asked Mar 06 '14 18:03

Thomas Johnson


1 Answers

It seems you're using classes as namespaces for your constants. You should ask yourself if the ABOVE and BELOW constants in every single class differs in something between each other.

If a differentiation is required (not just numeric difference, but semantic as well) then storing them in the class they represent is the best approach. On the other side if they have the same semantics in every class then you're not sticking to DRY principle and you're duplicating code.

A solution can be stored them at module level or create a class merely to contain the constants.

like image 105
Paulo Bu Avatar answered Sep 30 '22 06:09

Paulo Bu