4

I'd like to decorate every function in a module (curses in my case) with a logger, but haven't done something like this before. Can you tell me where to read some documentation.

I'd like something like:

import curses as mycurses
import curses_wrapper as curses

where curses_wrapper is my module, and should catch all calls to whatevermodulefunctions, log it, and call the "real" curses function afterwards.

For the curious: I am using PyCharm on windows, and would like to debug a curses program. Since PyCharm cannot provide me a terminal, I cannot really debug the program.

pihentagy
  • 5,975
  • 9
  • 39
  • 58
  • Perhaps this will help? http://stackoverflow.com/questions/10067262/automatically-decorating-every-instance-method-in-a-class Seems you could follow a similar reflection-based approach. – Christian Jun 04 '14 at 12:02
  • Similar, but I'd do it for a module, not for a class – pihentagy Jun 04 '14 at 12:32
  • 1
    the only thing I can propose to use own function for import and modify module attributes during import – oleg Jun 04 '14 at 13:22

1 Answers1

1

You can iterate over all of the functions in a module, decorate them, then add the decorated version to your own namespace. You can't iterate this process, since our basic Namespace object doesn't play all that well with inspect, but I'm sure this can be extended to support that thing if need be.

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))

foo!
False

Him
  • 5,257
  • 3
  • 26
  • 83