data validation when creating an object

Cameron Simpson cs at zip.com.au
Thu Jan 16 01:36:54 EST 2014


On 16Jan2014 15:53, Ben Finney <ben+python at benfinney.id.au> wrote:
> Roy Smith <roy at panix.com> writes:
> >  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.
> >
> > 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. […]
> 
> Even simpler: They are mistaken in what the constructor is named, in
> Python.
> Python classes have the constructor, ‘__new__’. I would agree with
> advice not to do anything but allocate the resources for a new instance
> in the constructor. [...]
> 
> Python instances have an initialiser, ‘__init__’. That function is for
> setting up the specific instance for later use. This is commonly
> over-ridden and many classes define a custom initialiser, which normally
> does some amount of work.
> 
> I don't think ‘__init__’ is subject to the conventions of a constructor,
> because *‘__init__’ is not a constructor*.

99% of the time this distinction is moot. When I call ClassName(blah,...),
both the constructor and initialiser are called.

Informally, there's a rule of thumb that making an object (allocate,
construct and initialise) shouldn't be needlessly expensive. Beyond
that, what happens depends on the use patterns.

This rule of thumb will be what Rita's encountered, perhaps stated
without any qualification regarding what's appropriate.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>

The problem with keeping an open mind is that my ideas all tend to fall out...
        - Bill Garrett <garrett at cs.unc.edu>



More information about the Python-list mailing list