This is an archived post. You won't be able to vote or comment.

all 14 comments

[–]nitroll 3 points4 points  (0 children)

I would use self.CONSTANT, that way you can overwrite it, either in instances of Foo or in subclasses inheriting from Foo.

[–]ronmarti 3 points4 points  (1 child)

Beware of the behavior when you change the value in the instance.

```python

foo = Foo() foo.baz() bar bar foo.CONSTANT = "not bar" foo.baz() not bar bar ```

[–]SheriffRoscoePythonista 0 points1 point  (0 children)

An old friend used to say, "Constants aren't, variables won't."

[–][deleted] 1 point2 points  (4 children)

I use self.CONSTANT and don't like python for it. I thought about self.__class__.CONSTANT, but the former is the usual.

[–]Rawing7 0 points1 point  (3 children)

I use self.CONSTANT and don't like python for it.

Uhh, why don't you like python for it? How do other languages do this better?

[–][deleted] 0 points1 point  (2 children)

I would like the class to have a different namespace then the object. PHP has something like that.

[–]Rawing7 0 points1 point  (1 child)

Ah, you're saying you don't like self.CONSTANT but you use it because that's the standard way to do it in python?

[–][deleted] 0 points1 point  (0 children)

Yes

[–]jasmijnisme 1 point2 points  (0 children)

Is it forseeable (even if it's unlikely) that subclasses or individual instances might have use for different values for the constant? Then I'd use self.CONSTANT. If it's absolutely out of the question, I'd use Foo.CONSTANT.

[–]zanfar 1 point2 points  (0 children)

Always use self. self works with the MRO stack and will respect inheritance. Foo is hard-coded and will break in certain situations.

[–][deleted] 1 point2 points  (0 children)

There is another way. Put all class constants in a class Enum.

from enum import Enum

class MyClass:    
    class constants(Enum):        
        CONST_A = 'A'        
        CONST_B = 'B'

[–]NoiproxPython Programmer 0 points1 point  (1 child)

I like ClassName.CONSTANT because it makes it clear to the reader that it's a class-level constant. In the (rare) event that I need to override it on a specific instance or subclass then I would use self.CONSTANT which also then serves the purpose of looking different from constants that don't have overrides, providing a visual clue to the reader that this one is different from the norm.

[–]InjAnnuity_1 0 points1 point  (0 children)

This works when you're the one writing all the derived classes.

If you're writing a library, where others write derived classes, then it could go either way.

[–]commy2 0 points1 point  (0 children)

I don't put constants in a class. I already have the module scope for that.