gpt4 book ai didi

exception - 返回 Exception 实例而不是在 Python 中引发它有什么缺点?

转载 作者:太空狗 更新时间:2023-10-30 02:14:21 26 4
gpt4 key购买 nike

我一直在用 python-couchdb 和 desktopcouch 做一些工作。在我提交的其中一个补丁中,我包装了来自 couchdb 的 db.update 函数。对于不熟悉 python-couchdb 的任何人,函数如下:

def update(self, documents, **options):
"""Perform a bulk update or insertion of the given documents using a
single HTTP request.

>>> server = Server('http://localhost:5984/')
>>> db = server.create('python-tests')
>>> for doc in db.update([
... Document(type='Person', name='John Doe'),
... Document(type='Person', name='Mary Jane'),
... Document(type='City', name='Gotham City')
... ]):
... print repr(doc) #doctest: +ELLIPSIS
(True, '...', '...')
(True, '...', '...')
(True, '...', '...')

>>> del server['python-tests']

The return value of this method is a list containing a tuple for every
element in the `documents` sequence. Each tuple is of the form
``(success, docid, rev_or_exc)``, where ``success`` is a boolean
indicating whether the update succeeded, ``docid`` is the ID of the
document, and ``rev_or_exc`` is either the new document revision, or
an exception instance (e.g. `ResourceConflict`) if the update failed.

If an object in the documents list is not a dictionary, this method
looks for an ``items()`` method that can be used to convert the object
to a dictionary. Effectively this means you can also use this method
with `schema.Document` objects.

:param documents: a sequence of dictionaries or `Document` objects, or
objects providing a ``items()`` method that can be
used to convert them to a dictionary
:return: an iterable over the resulting documents
:rtype: ``list``

:since: version 0.2
"""

如您所见,此函数不会引发 couchdb 服务器引发的异常,而是将它们返回到一个元组中,其中包含我们要更新的文档的 ID。

其中一位审稿人前往irc 上的#python 询问此事。在#python 中,他们建议使用标记值而不是异常。正如您可以想象的那样,仅一种方法是不切实际的,因为可以接收到许多可能的异常。我的问题是,除了使用异常更丑陋之外,使用异常而不是标记值还有什么缺点?

最佳答案

我认为在这种情况下返回异常是可以的,因为更新功能的某些部分可能会成功,而某些部分可能会失败。当您引发异常时,API 用户无法控制已经成功的内容。

关于exception - 返回 Exception 实例而不是在 Python 中引发它有什么缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2116972/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com