Using a decorator to *remove* parameters from a call

Aaron Brady castironpi at gmail.com
Mon Apr 13 09:42:48 EDT 2009


On Apr 13, 8:25 am, azeem <quadri.az... at gmail.com> wrote:
> On Apr 13, 3:45 pm, Aaron Brady <castiro... at gmail.com> wrote:
snip
> > @take_ab
> > def f( c= 42, d= 'some' ):
> >     print( 'in f, c= %r, d= %r'% ( c, d ) )
>
> > f( a= 'paramA', b= 'paramB', c= 'other number' )
>
> > /Output:
>
> > aval 'paramA' and bval 'paramB' popped
> > in f, c= 'other number', d= 'some'
>
> > As you can see, 'a', 'b', and 'c' were passed to 'f', but 'f' only
> > received 'c', as well as its default value for 'd'.  So long as you
> > only need to pass by keyword, not position, it's pretty easy.  It's
> > harder if the parameter you want might have been passed by either, and
> > you need to remove it from whichever one it was passed by.
>
> What does the @take_ab do ?

Hi.  It's a function decorator.  It replaces 'f' with another
function, which is impersonating it.

In particular, the meaning of this decorator is to remove any and all
occurrences of 'a' or 'b' in the keywords that are passed to 'f'.

So: If you call the impersonated 'f' like this:

f( 1, 2 )

Then the call proceeds as usual.  If you call it like this:

f( 1, 2, a= 'jamqar' ),

Then the real 'f' only receives this:

f( 1, 2 )

Unfortunately, to the world's loss, the original 'f' isn't practically
accessible anymore to anyone but the hijacker.  In fact, if you look
closely, you will find its internal name stamp is not 'f', but
'newfun'!




More information about the Python-list mailing list