delegation pattern via descriptor

kedra marbun kedra.marbun at gmail.com
Wed Jul 7 19:42:26 EDT 2010


On Jul 7, 2:46 am, Bruno Desthuilliers
<bdesth.quelquech... at free.quelquepart.fr> wrote:
> Gregory Ewing a écrit :
>
> > Bruno Desthuilliers wrote:
> >> kedra marbun a écrit :
>
> >>> if we limit our discussion to py:
> >>> why __{get|set|delete}__ don't receive the 'name' & 'class' from
> >>> __{getattribute|{set|del}attr}__
> >>> 'name' is the name that is searched
>
> >> While it would have been technically possible, I fail to imagine any use
> >> case for this.
>
> > I think he wants to have generic descriptors that are
> > shared between multiple attributes, but have them do
> > different things based on the attribute name.
>
> I already understood this, but thanks !-)
>
> What I dont understand is what problem it could solve that couldn't be
> solved more simply using the either _getattr__ hook or hand-coded
> delegation, since such a descriptor would be so tightly coupled to the
> host class that it just doesn't make sense writing a descriptor for this.

yeah, i finally can agree descriptor isn't supposed to be used as
delegation in general, it should be the job of __getattr__

however i still think passing name would open up some other
possibilities of use (not necessarily on the basis of sharing
descriptor), surely some of them (all of it?) are bad. sure as hell,
my example is an example of bad use. for now, i conclude that passing
name is too risky, it easily allows bad practices particularly against
the law of Demeter

thanks Bruno

btw, is there a common approach to let the interface of a class that
uses __getattr__, to include names that are delegated?

class A:
	def do_this(self): ...

class B:
	a = A()
	def do_that(self): ...

	def __getattr__(self, name):
		try:
			return types.MethodType(getattr(self.a, name), self)
		except AttributeError:
			raise AttributeError

how to make 'dir(B)' includes 'do_this', do i have to use __dir__? and
if i use __dir__, somewhat 'help(B)' doesn't work as usual, i haven't
check pydoc.py ;)



More information about the Python-list mailing list