1

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.

3
  • 5
    Why would you want statically typed variables for a dynamically typed language? Commented Apr 28, 2012 at 0:35
  • Define automatically check. You can always comapre the type. Commented Apr 28, 2012 at 0:51
  • If you care about static typing, you're using the wrong language. Commented Apr 28, 2012 at 0:51

2 Answers 2

2

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 ...

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

Comments

1

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))

1 Comment

I just came across this again and thought to myself "That's the perfect place for property". I was going to add it to my answer, but it turns out you've already done it. +1

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.