Descriptors: why __get__(obj,typ=None) instead of __get__(obj,typ)

S

Shalabh Chaturvedi

Almost everwhere the descriptor protocol is mentioned, it specifies
__get__(obj, typ=None). Why is a default value needed for the second
argument? In which case does Python call a descriptor without a second
argument?

Thanks,
Shalabh
 
M

Michael Hudson

Shalabh Chaturvedi said:
Almost everwhere the descriptor protocol is mentioned, it specifies
__get__(obj, typ=None).

Really? I thought it was "__get__(obj said:
Why is a default value needed for the second argument? In which case
does Python call a descriptor without a second argument?

It doesn't *look* like it does, ever.

/However/ the wrapper for tp_descr_get (typeobject.c:wrap_descr_get)
accepts 1 or 2 arguments translating an absent or None second argument
to NULL, so if you want to behave like C-implemented descriptors,
you'd better accept 1 or 2 arguments. IOW, it's just part of the
"descriptor protocol".

As to *why* it's like this... erm, not sure about that.

Cheers,
mwh
 
M

Mike C. Fletcher

Michael said:
....


It doesn't *look* like it does, ever.

/However/ the wrapper for tp_descr_get (typeobject.c:wrap_descr_get)
accepts 1 or 2 arguments translating an absent or None second argument
to NULL, so if you want to behave like C-implemented descriptors,
you'd better accept 1 or 2 arguments. IOW, it's just part of the
"descriptor protocol".

As to *why* it's like this... erm, not sure about that.
Possibly so that the interface is easier to use directly:

for prop in obj.getProperties():
try:
prop.__get__( obj )
except Exception:
argh()

Most of the time the class argument is unused (for simple property-like
code, anyway), so why not let people omit it when calling directly.
Seems like a good design choice to me.

Enjoy,
Mike

_______________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top