1

There are a few questions around SO that look into setting __class__ attribute in Python. It is mostly seen as unexpected and dangerous. For example, this question contains answers that discuss the downsides:

How dangerous is setting self.__class__ to something else?

However, are there any "good" uses of this language feature? Is there any criteria or principle as to when one should do this?

Community
  • 1
  • 1
MrFox
  • 1,244
  • 1
  • 11
  • 24
  • 1
    The second answer on your linked question gives about the only legitimate reason I can think of. *'Assigning the `__class__` attribute is useful if you have a long time running application and you need to replace an old version of some object by a newer version of the same class without loss of data.'* - either way, this is very much a 'list' question, I don't really see much benefit in listing obscure possible uses. – Gareth Latty May 06 '13 at 15:12
  • @Lattyware I was hoping for a guiding principle, not a list. I'll edit the question. – MrFox May 06 '13 at 15:15
  • 2
    The general guideline is: don't do it. In 9 years programming with Python, I've only ever done this once, and it was purely as a novelty to show that it could be done. – Nathan Ernst May 06 '13 at 15:28
  • 1
    `exec`, `eval` and rebinding `self.__class__` are the kind of "features" that have very very very few legitimate use cases. Think of custom interpreters or heavy code instrumentation... Well, been using Python since the 1.5.2 days and I have yet to find a use for any of these features (and I'm a happy metaclasses / descriptors / dynamic types/functions user). – bruno desthuilliers May 06 '13 at 15:51

0 Answers0