【问题标题】:Apply try/except to multiple Python class definitions将 try/except 应用于多个 Python 类定义
【发布时间】:2020-08-04 23:34:02
【问题描述】:

有没有一种方法可以将 try/except 逻辑应用于多个类定义,而无需在每个定义中都使用 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...

【问题讨论】:

    标签: python flask sqlalchemy flask-sqlalchemy python-decorators


    【解决方案1】:

    这可能不是一个好的做法,因为它确实降低了代码的可读性,但你可以像这样创建一个 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))
    

    再一次,我反对使用这种包装器来处理异常,因为从长远来看它们会让你的生活更加艰难,但这取决于你!

    【讨论】:

    • 有趣。是的,我知道这在装饰功能时有效。但我认为这不适用于类定义,因为它们没有返回任何东西..
    • @Kyle 然后您可以创建一个异常包装类并在其构造函数中调用一个抽象函数。然后扩展模块并用你想要的覆盖抽象函数。
    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 2021-04-24
    • 2018-03-19
    相关资源
    最近更新 更多