Python 用可变数量的位置参数和可选参数装饰方法

Python decorate methods with variable number of positional args and optional arg

我正在使用 SQLalchemy 编写我的第一个 Python (3.4) 应用程序。我有几种方法,它们的模式都非常相似。他们有一个可选参数 session,默认为 None。如果传递了 session,该函数将使用该会话,否则它会打开并使用一个新会话。例如,考虑以下方法:

def _stocks(self, session=None):
    """Return a list of all stocks in database."""
    newsession = False
    if not session:
        newsession = True
        session = self.db.Session()
    stocks = [stock.ticker for stock in session.query(Stock).all()]
    if newsession:
        session.close()
    return stocks

因此,作为 Python 的新手并渴望了解它的所有功能,我认为现在是学习一些 Python 装饰器的最佳时机。所以在大量阅读之后,像这样 this series of blog posts and this 很棒的 SO 答案,我写了以下装饰器:

from functools import wraps

def session_manager(func):
    """
    Manage creation of session for given function.

    If a session is passed to the decorated function, it is simply
    passed through, otherwise a new session is created.  Finally after
    execution of decorated function, the new session (if created) is
    closed/
    """
    @wraps(func)
    def inner(that, session=None, *args, **kwargs):
        newsession = False
        if not session:
            newsession = True
            session = that.db.Session()
        func(that, session, *args, **kwargs)
        if newsession:
            session.close()
        return func(that, session, *args, **kwargs)
    return inner

而且看起来效果很好。原来的方法现在缩减为:

@session_manager
def _stocks(self, session=None):
    """Return a list of all stocks in database."""
    return [stock.ticker for stock in session.query(Stock).all()]

但是,当我将装饰器应用到一个除了可选 session 之外还接受一些位置参数的函数时,我收到一个错误。所以试着写:

@session_manager
def stock_exists(self, ticker, session=None):
    """
    Check for existence of stock in database.

    Args:
        ticker (str): Ticker symbol for a given company's stock.
        session (obj, optional): Database session to use.  If not
            provided, opens, uses and closes a new session.

    Returns:
        bool: True if stock is in database, False otherwise.
    """
    return bool(session.query(Stock)
                .filter_by(ticker=ticker)
                .count()
                )

和 运行 像 print(client.manager.stock_exists('AAPL')) 给出了 AttributeError 和以下回溯:

Traceback (most recent call last):
  File "C:\Code\development\Pynance\pynance.py", line 33, in <module>
    print(client.manager.stock_exists('GPX'))
  File "C:\Code\development\Pynance\pynance\decorators.py", line 24, in inner
    func(that, session, *args, **kwargs)
  File "C:\Code\development\Pynance\pynance\database\database.py", line 186, in stock_exists
    .count()
AttributeError: 'NoneType' object has no attribute 'query'
[Finished in 0.7s]

所以我根据回溯猜测,我弄乱了参数的顺序,但我不知道如何正确地排序它们。除了 session 之外,我还有一些我想要修饰的函数可以接受 0-3 个参数。有人可以指出我方法中的错误吗?

我注意到的第一件事是你调用了两次装饰函数

@wraps(func)
    def inner(that, session=None, *args, **kwargs):
        newsession = False
        if not session:
            newsession = True
            session = that.db.Session()
        #calling first time
        func(that, session, *args, **kwargs)
        if newsession:
            session.close()
        #calling second time
        return func(that, session, *args, **kwargs)
    return inner

在第二次通话期间会话已经关闭。 此外,您不需要在装饰器函数中显式接受 thatsession 参数,它们已经在 argskwargs 中。看看这个解决方案:

@wraps(func)
def inner(*args, **kwargs):
    session = None
    if not 'session' in kwargs:
        session = that.db.Session()
        kwargs['session'] = session
    result = func(*args, **kwargs)
    if session:
        session.close()
    return result
return inner

您可能还想将会话关闭代码放在 finally 块中,那么即使装饰函数抛出异常,您也可以确保它已关闭

改变

def inner(that, session=None, *args, **kwargs):

def inner(that, *args, session=None, **kwargs):

return func(that, session, *args, **kwargs)

return func(that, *args, session=session, **kwargs)

有效:

def session_manager(func):

    def inner(that, *args, session=None, **kwargs):
        if not session:
            session = object()
        return func(that, *args, session=session, **kwargs)

    return inner


class A():

    @session_manager
    def _stocks(self, session=None):
        print(session)
        return True

    @session_manager
    def stock_exists(self, ticker, session=None):
        print(ticker, session)
        return True

a = A()
a._stocks()
a.stock_exists('ticker')

输出:

$ python3 test.py
<object object at 0x7f4197810070>
ticker <object object at 0x7f4197810070>

当您使用 def inner(that, session=None, *args, **kwargs) 时,任何第二个位置参数(计算 self)都被视为 session 参数。所以当你调用 manager.stock_exists('AAPL') session 时得到值 AAPL.