data validation when creating an object

Chris Angelico rosuav at gmail.com
Wed Jan 15 20:46:52 EST 2014


On Thu, Jan 16, 2014 at 12:25 PM, Cameron Simpson <cs at zip.com.au> wrote:
> However, I would also have obvious validity checks in __init__
> itself on the supplied values. Eg:
>
>   def __init__(self, size, lifetime):
>     if size < 1:
>       raise ValueError("size must be >= 1, received: %r" % (size,))
>     if lifetime <= 0:
>       raise ValueError("lifetime must be > 0, received: %r" % (lifetime,))
>
> Trivial, fast. Fails early. Note that the exception reports the
> receive value; very handy for simple errors like passing utterly
> the wrong thing (eg a filename when you wanted a counter, or something
> like that).

With code like this, passing a filename as the size will raise TypeError on Py3:

>>> size = "test.txt"
>>> size < 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() < int()

Yet another advantage of Py3 :)

ChrisA



More information about the Python-list mailing list