-1

I'm looking for recommendations for automated validation of instance variables in Python objects. The validation should occur immediately upon instantiation or setting.

For example, imagine a class like:

import recordtype
class TemperatureReading(recordtype.recordtype('TemperatureReading',
                                               ['lat','long','alt','temp'])):
    pass

I'd like to be able to constrain lat to +/- 90, long to +/- 180, alt >=0, and temp >=0 .

Writing getters and setters seems too un-Pythonic and tedious. Is there a better way?

Reece
  • 7,616
  • 4
  • 30
  • 46
  • 1
    Not sure I understand. Can't you do the validation in `__init__` or do you want the validation to take place whenever a user tries to do something like `reading.lat = 120`? For that you can use `property`. – mgilson Dec 09 '13 at 05:16

1 Answers1

0

Write getters and setters, but use Python properties so that it's less tedious for the user. You can do some simple metaprogramming, possibly with a metaclass, to make it less tedious for the class writer as well.

Community
  • 1
  • 1
Danica
  • 28,423
  • 6
  • 90
  • 122