Binarycrayon
Binarycrayon

Reputation: 1045

Testing whether class variable is repeatedly defined

Here is a quick example:

class KEY(object):
    A = 'a'
    A = 'b'
    B = 'b'

Is there a way to test that 'A' has been repeatedly defined in class 'KEY' regardless of the assigned value?

Upvotes: 1

Views: 94

Answers (2)

kindall
kindall

Reputation: 184455

If you're using Python 3, it's possible to do this cleanly using a dict subclass that only allows nonexisting keys to be set and the __prepare__ method of a metaclass. More info here. In Python 2 it's harder; I wrote a horrible hack to achieve it, with some limits.

Upvotes: 2

Thomas Orozco
Thomas Orozco

Reputation: 55303

Here's an attempt at answer:

Class variables are not going to work

You can't control redefinition for these. Basically, the metaclass is what is called to create your class, and it's passed a dict of attribute => value. We could say it's "already too late".

Using instance variables

You can control what happens when you do a.b = c after class instantiation, so what you could do is:

class RedefinitionMixin(object):
    def __setattr__(self, k, v):
        if hasattr(self, k):
            raise Exception('Attribute redefinition!')
        super(RedefinitionMixin, self).__setattr__(k, v)

class KEY(RedefinitionMixin, object):
    def __init__(self):
        self.A = 'a'
        self.A = 'b'
        self.B = 'b'

This may cause some unexpected behavior if you're already overriding __setattr__ though!

Note that this is only going to work in case you actually instantiate the class.
To circumvent the issue of using an instance, you could implement a singleton pattern.


Overall, I wouldn't recommend that solution, but that's the best I can come up with now.

Upvotes: 2

Related Questions