Encapsulation, inheritance and polymorphism
Roy Smith
roy at panix.com
Wed Jul 18 09:07:22 EDT 2012
In article <5006b2e2$0$29978$c3e8da3$5496439d at news.astraweb.com>,
Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> On Tue, 17 Jul 2012 09:52:59 -0400, Roy Smith wrote:
>
> > you could write in Python:
> >
> > # Type matching will get checked at run-time
> > def my_function(mpf, ot):
> > assert isinstance(mpf, MassivelyParallelFrobinator)
> > assert isinstance(ot, OtherThing)
>
> Keep in mind that assertions are not guaranteed to run. Code like the
> above is buggy, because if Python is run under the -O (optimize) flag,
> assertions will be stripped out.
One could equally say that "code like the above is efficient, because if
Python is run under the -O (optimize) flag, assertions will be stripped
out" :-)
> Better is to use explicit type checks and raise an exception yourself:
>
> if not isinstance(x, int):
> raise TypeError('expected an int, got %r' % x)
Maybe, but that's two lines where one does just fine. If you're going
to go for type-bondage, you might as well be efficient and succinct
about it.
More information about the Python-list
mailing list