如何定义使用钩子的函数?

2024-09-26 22:08:49 发布

您现在位置:Python中文网/ 问答频道 /正文

上下文

我正在编写一个函数,movefileset(),它将文件列表移动到不同的目标位置。glob表达式用于获取文件路径列表

movefileset()接受一个钩子seek_func,作为将在文件路径列表中的每个文件路径上调用的参数。钩子应该返回文件移动的目录movefileset()然后执行移动操作(以及一些簿记任务)

# Used for book-keeping    
tftb_entry = namedtuple('TransferTableEntry', ['FileNumber', 'SourceFile', 'Destination','FileDate'])

def movefileset(searchpath, globexpr, seek_func=None):
    '''seek_func is a function that takes a filename and returns the path'''
    if seek_func == None:
        logger.error("movefileset() failed: No seek_func provided. Check PyArchiver.py.")
        return

    # Get a list of files from `searchpath` using glob expression
    source_filepaths = glob(os.path.join(searchpath, globexpr))

    # Create a TransferTableEntry for each file returned by the glob operation, store them in a list
    transfertable = list()
    for filenum, sourcefilepath in enumerate(source_filepaths, 1):
        destination_directory = seek_func(filename)
        new_entry = tftb_entry(filenum, sourcefilepath)
    ...

问题陈述

我的问题是关于destination_directory = seek_func(filename)。作为一个正在编写movefileset()的人,他不知道作为seek_func传递的函数将是什么,他无法预测它需要的参数,我如何编写movefileset()以便调用将成功,而不管seek_func是什么,也不管它需要什么参数/关键字参数

可能的解决方案

SO: How to pass parameters to hook in python grequests中,解决方案建议建立一个hook\u工厂。我不太精通设计模式(这看起来像“工厂”设计模式),所以我不确定hook\u工厂到底应该如何使用(以及由谁使用)

我猜调用movefileset()的代码需要使用seek_func、参数/kwargs调用hook\u factory(),然后hook\u factory()将返回一个钩子,该钩子接受一个参数(filepath),然后应该传递给movefileset()

在这种情况下:

def seek_func_factory(seek_func, *seek_func_args, **seek_func_kwargs): 
    def seek_func_hook(filepath):
        return seek_func(filepath, *seek_func_args, **seek_func_kwargs)
    return seek_func_hook

但作为movefileset()的作者,这要求我在文档中指定所有seek_func钩子都应将filename作为第一个位置参数。如果指定seek_func的代码根本不使用filename(例如,用户希望将所有全局文件移动到一个目录),该怎么办。例如:

def move_to_single_directory():
   return r'C:\DestinationFolder'

客户需要这样定义:

def move_to_single_directory(filepath):
    return r'C:\DestinationFolder'

Tags: 文件to列表参数returndefseekhook

热门问题