1

I have a static class with a list of "colors" defined as fields. But each color is actually a time dependent function:

class Colors(object):
    @staticmethod
    def RED(t):
        return [255 * t, 0, 0]

Then, I have another class that will have these functions as fields:

class PathMaker(object):
    SUCCESS_COLOR = Colors.BLUE
    FAIL_COLOR = Colors.RED

But now, PathMaker.FAIL_COLOR is an unbound method, instead of a reference to Colors.RED.

Is there a better way of doing this? I could probably make SUCCESS_COLOR and FAIL_COLOR static methods, but that seems like a bad way of doing it.

6
  • you could switch to Python 3, which doesn't have the same method wrapping weirdness of 2.7. Commented Jul 10, 2014 at 17:51
  • Why do you think making FAIL_COLOR a staticmethod is a bad way? Commented Jul 10, 2014 at 17:55
  • General design advice: When something looks like a constant, it should be a constant. If it's not, don't make it look like one. Commented Jul 10, 2014 at 17:58
  • @Kevin: I'm not sure that will actually change anything here. Commented Jul 10, 2014 at 18:04
  • 1
    @BrenBarn, from my experiments, it seemed to make a difference: this Python 2 code gives a TypeError, but the same code in Python 3 produces the desired output. Commented Jul 10, 2014 at 18:06

1 Answer 1

3

Wrapping the reference with staticmethod works:

class Colors(object):
    @staticmethod
    def RED(t):
        return [255 * t, 0, 0]

class PathMaker(object):
    FAIL_COLOR = staticmethod(Colors.RED)

>>> PathMaker.FAIL_COLOR(1)
[255, 0, 0]
>>> PathMaker.FAIL_COLOR(2)
[510, 0, 0]

The reason is that the staticmethod descriptor causes accessing Colors.RED to "unwrap" the staticmethod and return the underlying "raw" function (not a method). Without using staticmethod in PathMaker, PathMaker rewraps this function into its own method, just as it would if you defined a function directly in the class body. By using staticmethod(Colors.RED), you can rewrap the unwrapped function into a staticmethod.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.