data validation when creating an object

Roy Smith roy at panix.com
Wed Jan 15 23:05:46 EST 2014


Rita <rmorgan466 at gmail.com> writes:
>> I know its frowned upon to do work in the __init__() method and only
>> declarations should be there.


In article <mailman.5555.1389834993.18130.python-list at python.org>,
 Ben Finney <ben+python at benfinney.id.au> wrote:

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

Weird, I was just having this conversation at work earlier this week.

There are some people who advocate that C++ constructors should not do a 
lot of work and/or should be incapable of throwing exceptions.  The pros 
and cons of that argument are largely C++ specific.  Here's a Stack 
Overflow thread which covers most of the usual arguments on both sides:

http://stackoverflow.com/questions/293967/how-much-work-should-be-done-in
-a-constructor

But, Python is not C++.  I suspect the people who argue for __init__() 
not doing much are extrapolating a C++ pattern to other languages 
without fully understanding the reason why.

That being said, I've been on a tear lately, trying to get our unit test 
suite to run faster.  I came across one slow test which had an 
interesting twist.  The class being tested had an __init__() method 
which read over 900,000 records from a database and took something like 
5-10 seconds to run.  Man, talk about heavy-weight constructors :-)



More information about the Python-list mailing list