首页 > 解决方案 > 关于有效参数映射的问题

问题描述

下面的代码使我更容易使用 Pymongo。

但我正在尝试重构它,因为我认为它太低效了。

由于我是初学者,我尝试了几次,但我对它并不满意,所以我想请教一些建议。

对不起,代码很乱。参考一下,

如果有任何图书馆或简单的例子,请告诉我。谢谢!

def find_(self, collection, find_value=None, projection=None, sort=None, skip=None, limit=None, multi_array=None, cursor=False):
    if sort is None:
       if skip is None and limit is None:
           cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection)
       if skip is not None and limit is None:
           cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).skip(skip)
       if skip is None and limit is not None:
           cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).limit(limit)
       if skip is not None and limit is not None:
           cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).skip(skip).limit(limit)
    else:
       arg = tuple((key, val) for key, val in sort.items())
       if skip is None and limit is None:
           cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).sort(arg)
       if skip is not None and limit is None:
           cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).sort(arg).skip(skip)
       if skip is None and limit is not None:
           cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).sort(arg).limit(limit)
       if skip is not None and limit is not None:
           cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).sort(arg).skip(skip).limit(limit)

标签: pythonpython-3.xargumentsrefactoring

解决方案


您的代码几乎与将要获得的效率一样高,因为cursor_result始终由一个完成所有实际工作的分支设置。唯一的问题是它有很多重复的代码。您可以通过一次处理每个选项来将其分解。

def find_(self, collection, find_value=None, projection=None, sort=None, skip=None, limit=None, multi_array=None, cursor=False):
    # Get the right path and call find
    cursor_result = self.db_path[collection].find(find_value, projection)

    # Sort if necessary
    if sort is not None:
        cursor_result = cursor_result.sort(tuple(sort.items()))

    # Skip if necessary
    if skip is not None:
        cursor_result = cursor_result.skip(skip)

    # Limit if necessary
    if limit is not None:
        cursor_result = cursor_result.limit(limit)

推荐阅读