Applying a decorator to a module

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Nov 27 19:23:55 EST 2008


On Thu, 27 Nov 2008 11:54:54 -0800, lkcl wrote:

> On Nov 27, 7:43 pm, s... at pobox.com wrote:
>>     lkcl> Very simple question: how do you apply a decorator to an
>>     entire lkcl> module?
>>
>> Function-by-function or class-by-class.  There is no decorator support
>> for modules.
> 
> awWww!  i'm going to quietly throw my toys out of my pram.
> 
> ... but seriously - doesn't that strike people as... a slightly odd
> omission?

No.

Strictly speaking, to talk about applying a decorator to a module means 
syntactic sugar for the following:

import mymodule
mymodule = decorator(mymodule)

Since it's only two lines, it's not a great hardship to expect people to 
call the decorator directly, instead of having syntactic sugar for it. 
The only hard part is to write the function decorator() itself -- and it 
isn't clear what that should possibly do. Function and class decorators 
wrap functions and classes, so presumably module decorators should wrap 
the module object itself.

But that doesn't seem to be what you want: you want it to look inside the 
module and wrap the individual functions and classes inside it. All of 
them? Wrap them with what? What about other objects? Should it wrap 
callable class instances ("functors") as well as the classes themselves? 
Metaclasses? Functions imported from other modules?

There's too many possible answers to these questions to expect this to be 
standard part of Python. In other words, this is an application-level 
task, not a language task, which means it's your job, not the standard 
library's.




-- 
Steven



More information about the Python-list mailing list