0

Assume that i have a following 'demo' class:

class demo(object):
   class_variable = None

Now whenever some one sets the 'class_variable', i need to validate the value (e.g. class_variable can have only values of type 'str').

demo.class_variable = 15
# here int value is assigned, i want to raise exception for such cases

This can be done for the instance variables by overriding the setattr(self,f,v) method.

How can it be done for the class variables ?

deepak
  • 349
  • 1
  • 5
  • 21
  • 1
    http://stackoverflow.com/q/5189699/1126841 is a near-duplicate; I'm not confident enough that it solves the problem to vote to close myself. – chepner Jun 09 '16 at 20:41

1 Answers1

2

By defining the appropriate __setattr__ on the metaclass for the class demo. As an example:

Create a MetaClass that defines the logic in its __setattr__ method (might want to perform a check based on the name of the attribute:

class DemoMeta(type):
    def __setattr__(self, name, value):
        if isinstance(value, str):
            return super(DemoMeta, self).__setattr__(name, value)
        else:
            raise ValueError("Only str values allowed")

Define a class which uses this meta class:

class demo(object):
    __metaclass__ = DemoMeta
    class_variable = None

And now, when you try to assign to class_variable a value that is not an instance of a string, DemoMeta.__setattr__ is going to get called, check and validate the assignment.

demo.class_variable = 12

Raises:

ValueError: Only str values allowed
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253