How to copy class objects?

Alex Martelli aleaxit at yahoo.com
Fri Feb 9 17:26:31 CET 2001


<matthias.oberlaender at daimlerchrysler.com> wrote in message
news:961103$a2e$2 at news.sns-felb.debis.de...
    [snip]
> But it seems it is sowewhat dangerous to give background information,
because
> it often distracts people from the real question, which is:
>
> How can I copy a class object?
> =========================
>
> Somebody suggested the copy module. But copy.copy does not apply to
classes!
>
> Ok, don't tell me that I don't need such a feature for the toy problem
given.
> It's solely for illustration. The real intent is much different.
> I can't accept subclassing, because I don't want instances of X and Xnew
have
> any base classes in common. So new.classobj won't work either!  Ok?

new.classobj, followed by setting the __bases__ attribute of the
new class object to an empty tuple, should do what you're asking.

Of course, the new class will not inherit anything from anybody,
since it will have no base classes whatsoever.  Alternatively,
you can recursively 'copy-class' up the inheritance DAG to
effect a (somewhat) 'deep-copy' of an entire DAG of related
classes, if that is what you actually want (not copying a [1]
class-object, but a whole graph of them).  Similarly, you will
have to copy (with the copy module, the new module, whatever)
any object to which class X has references, which you don't
want Xnew to share -- depending on what those "I don't want
this to be shared" objects are... it's hard to tell without
having any idea of the problem you're trying to solve this way
(e.g., the "not sharing any base classes" item is totally new
to me here, nor is it fully clear what it implies, as in,
emptying out the new class's __bases__ vs recursive copies).


Alex






More information about the Python-list mailing list