data validation when creating an object

Ben Finney ben+python at benfinney.id.au
Wed Jan 15 20:16:19 EST 2014


Rita <rmorgan466 at gmail.com> writes:

> I would like to do some data validation when its going to a class.
>
> class Foo(object):
>   def __init__(self):
>     pass
>
> I know its frowned upon to do work in the __init__() method and only
> declarations should be there.

Who says it's frowned on to do work in the initialiser? Where are they
saying it? That seems over-broad, I'd like to read the context of that
advice.

> So, should i create a function called validateData(self) inside foo?

If you're going to create it, ‘validate_data’ would be a better name
(because it's PEP 8 conformant).

> I would call the object like this
>
> x=Foo()
> x.validateData()

You should also be surrounding the “=” operator with spaces (PEP 8
again) for readability.

> Is this the preferred way? Is there a way I can run validateData()
> automatically, maybe put it in __init__?

It depends entirely on what is being done in those functions.

But in general, we tend not to write our functions small enough or
focussed enough. So general advice would be that, if you think the
function is going to be too long and/or doing too much, you're probably
right :-)

-- 
 \         “Nature hath given men one tongue but two ears, that we may |
  `\          hear from others twice as much as we speak.” —Epictetus, |
_o__)                                                      _Fragments_ |
Ben Finney




More information about the Python-list mailing list