簡體   English   中英

將 try/except 應用於多個 Python class 定義

[英]Apply try/except to multiple Python class definitions

有沒有辦法將 try/except 邏輯應用於多個 class 定義而無需在每個定義中都使用 try/except ?

例如,而不是:

def test_table(tablename):
    return Table(tablename, db.metadata, Column('id', Integer, primary_key=True))

class User(db.Model):
    try:
        __table__ = db.metadata.tables['user']
        __bind_key__ = 'secondary'
        # More attrs...
    except KeyError:
        __table__ = test_table('user')


class Policy(db.Model):
    try:
        __table__ = db.metadata.tables['policy']
        __bind_key__ = 'secondary'
        # More attrs...
    except KeyError:
        __table__ = test_table('policy')

我可以使用如下裝飾器應用邏輯:

@if_no_metadata_use_default('user')
class User(db.Model):
        __table__ = db.metadata.tables['user']
        __bind_key__ = 'secondary'
        # More attrs...

@if_no_metadata_use_default('policy')
class Policy(db.Model):
    __table__ = db.metadata.tables['policy']
    __bind_key__ = 'secondary'
    # More attrs...

一般來說,這可能不是一個好習慣,因為它確實降低了代碼的可讀性,但是您可以像這樣創建一個exception_wrapper裝飾器:

def exception_wrapper(func):
    def run(exception, on_exception, *args, **kwargs):
        try:
            return func(*args, **kwargs)
        except exception:
            on_exception()

    return run


def on_exception():
    pass


@exception_wrapper
def f(a, b):
    if a < b:
        raise NotImplementedError
    return a + b


print(f(NotImplementedError, on_exception, 10, 2))

同樣,我反對將這種包裝器用於異常,因為從長遠來看它們會使您的生活更加艱難,但這取決於您!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM