is decorator the right thing to use?

Paul McGuire ptmcg at austin.rr.com
Fri Sep 26 10:18:28 EDT 2008


On Sep 25, 10:41 am, "Dmitry S. Makovey" <dmi... at athabascau.ca> wrote:
> Diez B. Roggisch wrote:
> > Dmitry S. Makovey schrieb:
> >> Dmitry S. Makovey wrote:
> >>> In my real-life case A is a proxy to B, C and D instances/objects, not
> >>> just one.
>
> >> forgot to mention that above would mean that I need to have more than one
> >> decorator function like AproxyB, AproxyC and AproxyD or make Aproxy
> >> smarter about which property of A has instance of which class etc.
>
> > __getattr__?
>
> see, in your code you're assuming that there's only 1 property ( 'b' )
> inside of A that needs proxying. In reality I have several. So in your code
> self._delegate should be at least a tupple or a list. Plus what you're
> doing - you just promiscuously passing any method not found in Proxy to
> self._delegate which is not what I need as I need to pass only a subset of
> calls, so now your code needs to acquire dictionary of "allowed" calls, and
> go over all self._delegates to find if any one has it which is not
> efficient since there IS a 1:1 mapping of A::method -> B::method so lookups
> shouldn't be necessary IMO (for performance reasons).
>

No, really, Diez has posted the canonical Proxy form in Python, using
__getattr__ on the proxy, and then redirecting to the contained
delegate object.  This code does *not* assume that only one property
('b'? where did that come from?) is being redirected - __getattr__
will intercept all attribute lookups and redirect them to the
delegate.

If you need to get fancier and support this single-proxy-to-multiple-
delegates form, then yes, you will need some kind of map that says
which method should delegate to which object.  Or, if it is just a
matter of precedence (try A, then try B, then...), then use hasattr to
see if the first delegate has the given attribute, and if not, move on
to the next.

>
> I'm trying to figure out if there
> is another way to use decorators for my scenario or is there another way of
> achieving the same thing without using decorators and without bloating up
> the code with alternative solution.
>
> Another way could be to use Metaclass to populate class with method upon
> declaration but that presents quite a bit of "special" cruft which is more
> than I have to do with decorators :) (but maybe it's all *necessary* ? )
>

Your original question was "is decorator the right thing to use?"  For
this application, the answer is "no".  It sounds like you are trying
to force this particular to solution to your problem, but you are
probably better off giving __getattr__ intercepting another look.

-- Paul



More information about the Python-list mailing list