new.instancemethod

Alex Martelli aleaxit at yahoo.com
Sat May 19 07:03:31 EDT 2001


<James_Althoff at i2.com> wrote in message
news:mailman.990222627.23768.python-list at python.org...
>
> Alex Martelli wrote:
> >...then class 'Tweak' will have ONE base class, rather than the variety
> >of specific base classes it will need for this use:
>
> which is ok if the instances that we want to tweak are all instances of
the
> same class -- which is a bad assumption in general, so I agree with you:

It's bad if we want to change object-classes as our tweak strategy (which
is the hypothesis under discussion:-) since previously-tweaked objects will
have different classes.

> the class statement needs to be in the def body (which, to me, decreases
> the attractiveness of that approach compared to the first approach).

I don't find local def or class statements (i.e. ones inside function
bodies) to be a problem per se.


> >"Judiciously" is a keyword
> >here I think -- it's great for experimental interactive specialized
> >programming frameworks, but I can't think of a case I would WANT
> >to use such black magic in _production_ code.
>
> Presumably when you say black magic you are referring to the second
> approach (changing the __class__ attribute of an instance) and not the
> first approach (using "new.instancemethod")?  Because if both, then I'm

Both!  Anything from module new qualifies as very-dark-gray (at the
lightest-shade:-) magic in my opinion.  As does changing __class__...

> back to my original interest of looking for a good example of (needing)
and
> practice for (implementing) "instance-specific behavior" that would be
> reasonable to use -- even in production code.  I believe you are saying
> that approach 1 is a reasonable way to go in your experience (if the need
> arises such as in your bridge game example).

The bridge stuff is definitely an "experimental interactive specialized
programming framework", not "production code".  I have no qualms
against dark-hued magic (metaprogramming) of any kind in such a
setting.  "Reasonable to use even in production code" is harder to
call.  One case for changing __class__ that I'd use without qualms:
objects that exist in a few different "major states" with polymorphic
and very different behaviors, say for example a "skeleton state" where
the object only holds minimal information to 'restore itself', and upon
any method call transitions to "full-fledged state", restoring data and
changing its own __class__ -- I prefer this to having to test a state
variable in each method... in a language that does not allow state
change I'd introduce an indirectness (the object being an envelope
for different 'letter-objects' over time), but changing __class__ is
more direct, immediate, and simpler.  But that's not "instance
specific behavior"... and only moderate-light-gray magic anyway...


Alex






More information about the Python-list mailing list