There is a similar question here, but if refers to "reclassing", while i want a subclass.
Suppose, i have a Django/SQLAlchemy exception IntegrityError
, and i want to have a subclass of it called AlreadyExists
for a special case when a unique constraint was violated:
try:
...
except IntegrityError as exc:
if ('violates unique constraint '
'"customer_wish_customer_product_unique"') in exc.message:
raise AlreadyExists(exc)
I don't want to do just a subclass, because IntegrityError.__init__
has many arguments, which i don't want to, manually extract from existing IntegrityError
instance and feed them to the parent __init__
.
So i came up with the following code:
class AlreadyExists(IntegrityError):
def __new__(cls, sa_exc):
sa_exc.__class__ = cls # replace the class
return sa_exc # but do not create new object
def __init__(self, *args):
pass # do nothing, as no new object was created
What do you think about the idea itself and can you suggest a better implementation?