doctest environment question

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue May 22 11:18:13 EDT 2007


En Tue, 22 May 2007 08:57:29 -0300, tag <thomas.guest at gmail.com> escribió:

> On 22 May, 10:11, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:
>> The version given by Peter Otten may do what you want, but I'd consider  
>> if
>> you really need an announce_function in the first place, given all the
>> other ways you already have to do the same thing.
>> Implicitely rebinding globals does not look good.
>
> Thanks for the advice Gabriel. The use case I have is that I'd like to
> be able to decorate classes and even modules in this way:
>
> import announce
> import spam
> announce.announce_module(spam)
>
> ... code which calls into spam module
>
> Here, "announce.announce_module" has a look in "spam", finds all the
> functions and instancemethods, and decorates them (rebinds them) by
> announcing calls to these functions and instancemethods.
>
> It's something I've found useful, though clearly the behaviour of
> "spam" has been drastically changed. I'd appreciate advice on better
> ways to achieve this kind of thing, or why it doesn't look good.

Ah, then you *have* a reference to the containing module. announce_module  
might be something like this:

def announce_module(module):
     for fname in find_all_functions_by_name_in_module(module):
         function = getattr(module, fname)
         setattr(module, fname, announce_function(function))

And no need to guess anything. It works even if the original function name  
is not the same as the name used in the module (this may happen when you  
assign a function with another name).
Remember "Explicit is better than implicit" and "In the face of ambiguity,  
refuse the temptation to guess."

-- 
Gabriel Genellina




More information about the Python-list mailing list