Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for properties' validity in Python classes

Tags:

python

Where should I write codes for checking validity of class' properties? (For examples: "amount" should be a positive integer, "email" should be a string with correct e-mail formatting) At the setter methods, At somewhere I use that (using try/catch), or others.

If I check validity at setter methods, it may be looked ugly (like type checking). But if I check it when using it, duplicated code may appeared when it is used many times.

(Sorry for my poor English.)

like image 337
champjss Avatar asked Feb 03 '10 18:02

champjss


People also ask

How do you validate a class attribute in Python?

Here is the code using descriptors. Every attribute becomes a descriptor which is a class with methods __get__ and __set__ . When the attribute value is set like self.name=name , then __set__ is called. When the attribute is retrieved like print(self.name) , then __get__ is called.

Do Python classes have properties?

Class Properties In Python, a property in the class can be defined using the property() function. The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#.

What is __ str __ in Python?

Python __str__()This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.


2 Answers

Definitely do it in the setter, if you need to do it at all.

First, the setter is probably called less often than the getters, so you're doing less work.

Second, you catch the problem earlier.

Third, it keeps the internal state of the object consistent. Keeping out bad data means you know that your object is "right".

like image 121
Ned Batchelder Avatar answered Oct 23 '22 04:10

Ned Batchelder


If it looks like ugly type checking, that may be because it is. If "amount" absolutely needs to be a positive integer, and the rest of the module will fail badly if it is not, then you need to do some type checking.

The python way of doing this, though, is only to check for the actual properties that you require.

In the positive integer example, that means not checking that the value is an Int object, but checking instead that it has a value, and that the value is > 0. This lets other programmers pass your methods objects that act like numbers, without strictly constraining their type.

The same thing goes for the email example -- check that it is properly formatted (matches whatever email regex you are using), but don't insist that it is an instance of the Str class. Don't insist on anything in your validity checking except properties that you are actually going to use.

like image 39
Ian Clelland Avatar answered Oct 23 '22 05:10

Ian Clelland