Assigning to __class__ : bad form?

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Fri Jun 6 21:02:24 CEST 2008


On 6 juin, 19:51, The Pythonista <n... at this.time> wrote:
> I've been wondering for a while about whether assigning to __class__ is
> bad form or not.  Specifically, I mean doing so when some other method of
> implementing the functionality you're after is available (i.e. using an
> adapter, or something like the strategy pattern).
>
> To give an example and a non-example of what I'm talking about, consider
> the following recipes from the online Python Cookbook:
>
> Ring Buffer:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429
>
> In this case, I think the assignment to __class__ just obfuscates things,
> and the example would be better coded as a single class.
>
> On the other hand,
>
> Fast copy of an object having a slow __init__ : http://
> aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66507
>
> This seems like a reasonable use case for assigning to __class__ (except
> that it's already implemented in the 'new' module, but, read the Martelli-
> bot's comments near the end of the recipe).  I consider this a reasonable
> use case for assigning to __class__, because, short of the 'new' module,
> I don't see any other way to accomplish it.
>
> So, what is the opinion of the broader Python community?

My first opinion is that your formulation, ie "assigning *to*
__class__" is perhaps a bit misleading. What you're talking about is
rebinding the __class__ attribute, while, from your subject line, I
thought you were talking about reassigning to (rebinding) a class
attribute from the instance, ie : self.__class__.attrib = value.

Now to the point:

>  Is code that
> assigns to __class__ just clever trickiness to be avoided, or is it
> sometimes a good thing?

Both, definitively !-)

Like most of Python's "advanced" features, it's nice to have it
because it can easily solve problems that would otherwise be at best a
PITA, but it's not something you use on a daily basis - nor without
thinking twice. And obviously, there's no clear rule here, except good
taste and common sense. Anyway, the mere fact that you're asking
yourself if it's a good idea in such or such case is a probably a good
indication that you'll find out by yourself the day you'll be tempted
to use this trick whether it's a good or bad idea in this particular
context.



More information about the Python-list mailing list