Skip to main content
 首页 » 编程设计

Python:functools,方法的包装装饰器:使用 '' 时使 ipython 返回正确的定义

2024年10月25日8linjiqin

我正在使用 functools 制作一个装饰器,它允许我 记录方法调用的详细信息。

我在这里得到了很多帮助来写它......它不是我自己的,但我仍然 学习它是如何工作的……

我经常使用 ipython,当我使用时:

import Tools 
imagetools = Tools.Tools() 
imagetools.save_new_image ? 
 
Type:       instancemethod 
String Form:<bound method ImageTools.save_new_image of <ImageTools.ImageTools object      at    0x305d1d0>> 
File:       /fs/corpus6/dpc/workspace/python/Modules/MiscTools.py 
Definition: imagetools.save_new_image(self, *args, **kwargs) 
Docstring:  <no docstring> 

这是我的问题行...除此之外我还没有编写文档字符串...:|

Definition: imagetools.save_new_image(self, *args, **kwargs) 

我希望它是:

save_new_image_clone(self, data, header, outfile,  coordmap) 

包装器:

import functools 
 
def log_method(func): 
 
@functools.wraps(func) 
def wrapper(self, *args, **kwargs): 
    self.__doc__ = func.__doc__ 
    # allows me to put the wrapper in helper methods that are sometimes major steps 
    if check_for_True_in_last_arg(*args): 
        log.debug('''Last arg is "True" which could indicate the caller  
intends the log to work on this method. For that behaviour, use the keyword arg:  log_this=True''') 
 
    if 'log_this' in kwargs and kwargs['log_this'] is not False:  
        args_name = inspect.getargspec(func)[0][1:] #drop the 'self' arg 
        args_dict = dict(list(itertools_izip(args_name, args)) + list(kwargs.iteritems())) 
        method_name = wrapper.__name__ 
        args_dict_string = '\nMETHOD: ' + method_name + '\n' 
 
        for k,v in args_dict.iteritems(): 
            if type(v) is not np.ndarray: 
                args_dict_string += "%s: %s\n" %(k,v) 
 
            elif type(v) is np.ndarray: 
                args_dict_string += "NUMPY ARRAY:%s \nSHAPE:%s\n" %(k, str(v.shape)) 
 
        args_dict_string += '\n' 
        log.info(args_dict_string) 
 
    return func(self, *args, **kwargs)  
 
return wrapper 

更新: 在 ipython 中,我这样做是为了看看发生了什么,但它对我没有帮助......

help?? 
Type:       _Helper 
String Form:Type help() for interactive help, or help(object) for help about object. 
File:       /usr/lib64/python2.7/site.py 
Definition: help(self, *args, **kwds) 
Source: 
 
class _Helper(object): 
"""Define the builtin 'help'. 
This is a wrapper around pydoc.help (with a twist). 
 
""" 
 
def __repr__(self): 
    return "Type help() for interactive help, " \ 
           "or help(object) for help about object." 
def __call__(self, *args, **kwds): 
    import pydoc 
    return pydoc.help(*args, **kwds) 
 
Call def:   help(self, *args, **kwds) 

请您参考如下方法:

您正在尝试做的事情——制作一个调用签名与被装饰的函数相同的装饰器——从头开始并不是一件简单的事情。有一个第三方模块,称为 decorator ,但是可以这样做:

import decorator 
 
@decorator.decorator 
def log_method(func, *args, **kwargs): 
    # allows me to put the wrapper in helper methods that are sometimes major steps 
    if check_for_True_in_last_arg(*args): 
        log.debug('''Last arg is "True" which could indicate the caller  
intends the log to work on this method. For that behaviour, use the keyword arg:  log_this=True''') 
 
    if 'log_this' in kwargs and kwargs['log_this'] is not False:  
        args_name = inspect.getargspec(func)[0][1:] #drop the 'self' arg 
        args_dict = dict(list(itertools_izip(args_name, args)) + list(kwargs.iteritems())) 
        method_name = wrapper.__name__ 
        args_dict_string = '\nMETHOD: ' + method_name + '\n' 
 
        for k,v in args_dict.iteritems(): 
            if type(v) is not np.ndarray: 
                args_dict_string += "%s: %s\n" %(k,v) 
 
            elif type(v) is np.ndarray: 
                args_dict_string += "NUMPY ARRAY:%s \nSHAPE:%s\n" %(k, str(v.shape)) 
 
        args_dict_string += '\n' 
        log.info(args_dict_string) 
 
    return func(self, *args, **kwargs)  
 
class Tools(object): 
    @log_method 
    def save_new_image(self, data, header, outfile, coordmap): 
        """ 
        Jazz the snaz output baz 
        """ 

然后从 IPython:

In [14]: imagetools = Tools() 
 
In [15]: imagetools.save_new_image? 
Type:       instancemethod 
String Form:<bound method Tools.save_new_image of <__main__.Tools object at 0xae1e20c>> 
File:       /tmp/python-2973tNk.py 
Definition: imagetools.save_new_image(self, data, header, outfile, coordmap) 
Docstring:  Jazz the snaz output baz 

如果您想查看实现此目的的 Python 代码,请参阅 the decorator.FunctionMaker class .它使用 inspect 找出原始函数的签名,然后使用字符串格式编写定义修饰函数的 def-statement。然后它调用 exec code in evaldict 来执行字符串。