0

ここに同様の質問がありますが、「再分類」を参照している場合は、サブクラスが必要です。

Django/SQLAlchemy の例外があり、一意の制約に違反した場合に特別なケースでIntegrityErrorそのサブクラスを呼び出したいとします。AlreadyExists

    try:
         ...
    except IntegrityError as exc:
        if ('violates unique constraint '
                '"customer_wish_customer_product_unique"') in exc.message:
            raise AlreadyExists(exc)

私はしたくないIntegrityError.__init__多くの引数を持っているため、既存のIntegrityErrorインスタンスから手動で抽出し、それらを親にフィードするため、サブクラスだけを実行したくありません__init__

だから私は次のコードを思いついた:

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

アイデア自体についてどう思いますか? より良い実装を提案できますか?

4

0 に答える 0