tkf
tkf

Reputation: 3020

Python module for statically typed class attributes

I want my Python class to automatically check the type of value when assigning it to an attribute.

There is enthought's traits module and IPython has a pure python version as its sub module IPython.utils.traitlets. Are there any similar modules? If that module has automatic command line argument parser to set these attribute, that would be better.

EDIT: Thanks for the snippets. But I want Python library. If there exists library to do that, I don't want to reimplement by myself.

Upvotes: 1

Views: 155

Answers (2)

SingleNegationElimination
SingleNegationElimination

Reputation: 156158

almost any manner of "automatic" behavior can be determined on object attributes using python descriptors. The simplest sort of descriptor is property:

class Foo(object):
    @property
    def bar(self):
        try:
            return self._bar
        except AttributeError:
            return "default value"

    @bar.setter
    def bar(self, value):
        if isinstance(value, Baz): # for some other type "Baz"
            self._bar = value
        else:
            raise ValueError("wrong type for attribute bar,"
                             " expected %r, got %r" % (Baz, type(value))

Upvotes: 1

mgilson
mgilson

Reputation: 309929

I don't know about traits ... but if you want to check the type of an object when it is assigned, you can override __setattr__ to check that...

class MyClass(object):
   def __setattr__(self, attr, val):
       if attr == 'my_attr':
           if not isinstance(val, str):
              raise ValueError('my_attr must be a string!')
           else:
              object.__setattr__(self, attr, val)
       else:
           object.__setattr__(self, attr, val)

a = MyClass()
a.my_attr = "Hello World!"  # This is OK
a.my_attr = 1               # This is not: ValueError

But I really wouldn't recommend doing this without a really good reason ...

Upvotes: 2

Related Questions