Decorator for Enforcing Argument Types

John Machin sjmachin at lexicon.net
Fri Dec 22 04:43:28 EST 2006


Duncan Booth wrote:
> "John Machin" <sjmachin at lexicon.net> wrote:
>
> >> > if isinstance(....
> >> >     action_for_type1(...
> >> > # big snip
> >> > elif isinstance(...
> >> >     action_typeN( ...
> >> > # no else statement
> >>
> >> Ouch.. someone must have skipped his/her OO class...
> >
> > Quite possibly :-) but that's not the problem here.
> >
> > The method in question might be called say emit_generic(self,
> > any_type_of obj) and so one bunch of isinstance calls is actually
> > needed, but not two bunches. So: lose the decorator and add an else and
> > a raise at the end.
> >
> > There is a secondary problem: annoying the crap out of callers who
> > often know what type they have and want an emit_real which would take
> > an int, a long, or a float and an emit_strg and ... (yes, almost all
> > the possible types are that simple) which wouldn't go through even one
> > chain of isinstance calls.
> >
>
> I think the point that was being made was that the method's body should be
> something like:
>
>    actions[type(arg)](...)
>
> which not only avoids all of the isinstance calls but also the else and the
> raise at the end.

You are saying that you think that George thinks that they are teaching
efficient coding methods in OO classes??




More information about the Python-list mailing list