【问题标题】:decorate standard python module装饰标准python模块
【发布时间】:2014-06-04 11:55:52
【问题描述】:

我想用记录器装饰模块中的每个函数(在我的例子中是诅咒),但以前没有做过这样的事情。你能告诉我在哪里可以阅读一些文档吗?

我想要类似的东西:

import curses as mycurses
import curses_wrapper as curses

其中 curses_wrapper 是我的模块,应该捕获对whatevermodulefunctions 的所有调用,记录它,然后调用“真正的”curses 函数。

对于好奇:我在 Windows 上使用 PyCharm,并想调试一个 curses 程序。由于 PyCharm 无法为我提供终端,我无法真正调试程序。

【问题讨论】:

  • 也许这会有所帮助? stackoverflow.com/questions/10067262/… 似乎您可以采用类似的基于反射的方法。
  • 类似,但我会为一个模块而不是为一个类这样做
  • 我唯一可以建议在导入过程中使用自己的函数进行导入和修改模块属性

标签: python


【解决方案1】:

您可以iterate over all of the functions in a module,装饰它们,然后将装饰后的版本添加到您自己的命名空间。你不能重复这个过程,因为我们的基本Namespace 对象不能很好地与inspect 配合使用,但我相信如果需要的话可以扩展它来支持那个东西。

import inspect
import types

class Namespace(object):
    pass

def decorate_module(module, decorator):
    namespace = Namespace()
    for n,v in inspect.getmembers(module):
        if isinstance(v, types.FunctionType):
            v = decorator(v)
        setattr(namespace, n, v)
    return namespace

def foo_decorator(f):
    def foo_func(*args, **kwargs):
        print("foo!")
        return f(*args, **kwargs)
    return foo_func

inspect = decorate_module(inspect, foo_decorator)

print(inspect.ismodule(inspect))

嘘!
假的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-30
    • 2017-11-28
    • 1970-01-01
    • 2015-05-15
    • 2011-02-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多