简体   繁体   English

将 try/except 应用于多个 Python class 定义

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

is there a way to apply try/except logic to multiple class definitions without a try/except in every definition?有没有办法将 try/except 逻辑应用于多个 class 定义而无需在每个定义中都使用 try/except ?

For example, instead of:例如,而不是:

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')

I could apply logic with a decorator like:我可以使用如下装饰器应用逻辑:

@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...

This might not be a good practice in general since it really decreases your code readablity, but you can create an exception_wrapper decorator like this:一般来说,这可能不是一个好习惯,因为它确实降低了代码的可读性,但是您可以像这样创建一个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))

Again, I'm against using this kind of wrappers for exceptions since they will make your life harder in the long run, but it's up to you!同样,我反对将这种包装器用于异常,因为从长远来看它们会使您的生活更加艰难,但这取决于您!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM