Repository navigation
classmethod doesn't honour descriptor protocol of wrapped callable #63272
Copy link
Copy link
Closed
Labels
3.8 (EOL)end of lifeend of lifeinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancementA feature request or enhancement
Description
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee = 'https://github.com/rhettinger'
closed_at = <Date 2019-08-24.22:37:58.662>
created_at = <Date 2013-09-22.13:22:44.087>
labels = ['interpreter-core', 'type-feature', '3.8']
title = "classmethod doesn't honour descriptor protocol of wrapped callable"
updated_at = <Date 2021-11-19.19:12:24.582>
user = 'https://bugs.python.org/grahamd'bugs.python.org fields:
activity = <Date 2021-11-19.19:12:24.582>
actor = 'lukasz.langa'
assignee = 'rhettinger'
closed = True
closed_date = <Date 2019-08-24.22:37:58.662>
closer = 'rhettinger'
components = ['Interpreter Core']
creation = <Date 2013-09-22.13:22:44.087>
creator = 'grahamd'
dependencies = []
files = ['31842', '42737']
hgrepos = []
issue_num = 19072
keywords = ['patch']
message_count = 23.0
messages = ['198274', '198672', '198673', '198679', '198682', '201512', '201523', '201572', '201713', '201714', '264911', '264916', '321217', '321222', '321227', '350404', '379509', '379510', '384405', '397547', '397551', '406607', '406617']
nosy_count = 12.0
nosy_names = ['gvanrossum', 'rhettinger', 'pitrou', 'grahamd', 'ionelmc', 'daniel.urban', 'lukasz.langa', 'berker.peksag', 'serhiy.storchaka', 'eriknw', 'miss-islington', 'iritkatriel']
pr_nums = ['8405', '22757', '22934', '22935', '27115', '27162', '29634', '29643']
priority = 'normal'
resolution = 'fixed'
stage = 'resolved'
status = 'closed'
superseder = None
type = 'enhancement'
url = 'https://bugs.python.org/issue19072'
versions = ['Python 3.8']Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
3.8 (EOL)end of lifeend of lifeinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancementA feature request or enhancement
Activity
grahamd commentedon Sep 22, 2013
The classmethod decorator when applied to a function of a class, does not honour the descriptor binding protocol for whatever it wraps. This means it will fail when applied around a function which has a decorator already applied to it and where that decorator expects that the descriptor binding protocol is executed in order to properly bind the function to the class.
A decorator may want to do this where it is implemented so as to be able to determine automatically the context it is used in. That is, one magic decorator that can work around functions, instance methods, class methods and classes, thereby avoiding the need to have multiple distinct decorator implementations for the different use case.
So in the following example code:
A failure is encountered of:
BoundWrapper.__call__() () {}
__wrapped__.__self__ <class '__main__.Class'>
Class.function_cm_inner() <class '__main__.Class'>
IOW, everything is fine when the decorator is applied around the classmethod, but when it is placed inside of the classmethod, a failure occurs because the decorator object is not callable.
One could argue that the error is easily avoided by adding a __call__() method to the Wrapper class, but that defeats the purpose of what is trying to be achieved in using this pattern. That is that one can within the bound wrapper after binding occurs, determine from the __self__ of the bound function, the fact that it was a class method. This can be inferred from the fact that __self__ is a class type.
If the classmethod decorator tp_descr_get implementation is changed so as to properly apply the descriptor binding protocol to the wrapped object, then what is being described is possible.
Having it honour the descriptor binding protocol also seems to make application of the Python object model more consistent.
A patch is attached which does exactly this.
The result for the above test after the patch is applied is:
BoundWrapper.__call__() () {}
__wrapped__.__self__ <main.Class object at 0x10ad237d0>
Class.function_im() <main.Class object at 0x10ad237d0>
BoundWrapper.__call__() () {}
__wrapped__.__self__ <class '__main__.Class'>
Class.function_cm_inner() <class '__main__.Class'>
BoundWrapper.__call__() () {}
__wrapped__.__self__ <class '__main__.Class'>
Class.function_cm_outer() <class '__main__.Class'>
That is, the decorator whether it is inside or outside now sees things in the same way.
If one also tests for calling of the classmethod via the instance:
Everything again also works out how want it:
BoundWrapper.__call__() () {}
__wrapped__.__self__ <class '__main__.Class'>
Class.function_cm_inner() <class '__main__.Class'>
BoundWrapper.__call__() () {}
__wrapped__.__self__ <class '__main__.Class'>
Class.function_cm_outer() <class '__main__.Class'>
FWIW, the shortcoming of classmethod not applying the descriptor binding protocol to the wrapped object, was found in writing a new object proxy and decorator library called 'wrapt'. This issue in the classmethod implementation is the one thing that has prevented wrapt having a system of writing decorators that can magically work out the context it is used in all the time. Would be nice to see it fixed. :-)
The wrapt library can be found at:
https://github.com/GrahamDumpleton/wrapt
http://wrapt.readthedocs.org
The limitation in the classmethod implementation is noted in the wrapt documentation at:
http://wrapt.readthedocs.org/en/v1.1.2/issues.html#classmethod-get
rhettinger commentedon Sep 30, 2013
I don't think it was ever intended that decorators be chained together.
The whole point is to control binding behavior during dotted look-up (when __getattribute__ is called) and not in other circumstances (such as a direct lookup in a class dictionary).
Note that classmethods typically wrap regular functions which have both __call__ and __get__ methods. The classmethod object intentionally invokes the former instead of the latter which would unhelpfully create an inner bound or unbound method.
grahamd commentedon Sep 30, 2013
The classmethod __get__() method does:
So it isn't intentionally calling __call__(). If it still doing binding, but doing it by calling PyMethod_New() rather than using __get__() on the wrapped function. Where it wraps a regular function the result is same as if __get__() was called as __get__() for a regular function internally calls PyMethod_New() in the same way.
By not using __get__(), you deny the ability to have chained decorators that want/need the knowledge of the fact that binding was being done. The result for stacking multiple decorators which use regular functions (closures) is exactly the same, but you open up other possibilities of smarter decorators.
rhettinger commentedon Sep 30, 2013
I'll take a look at this in more detail in the next week or so.
grahamd commentedon Sep 30, 2013
If you have the time, would be great if you can have a quick look at my wrapt package. That will give you an idea of where I am coming from in suggesting this change.
http://wrapt.readthedocs.org/en/latest/
http://wrapt.readthedocs.org/en/latest/issues.html
http://wrapt.readthedocs.org/en/latest/decorators.html
http://wrapt.readthedocs.org/en/latest/examples.html
In short, aiming to be able to write decorators which are properly transparent and aware of the context they are used in, so we don't have this silly situation at the moment where it is necessary to write distinct decorators for regular functions and instance methods. A classmethod around another decorator was the one place things will not work as would like to see them work.
I even did a talk about writing better decorators at PyCon NZ. Slides with notes at:
http://lanyrd.com/2013/kiwipycon/scpkbk/
Thanks.
rhettinger commentedon Oct 28, 2013
Antoine, do you have any thoughts on this proposal?
pitrou commentedon Oct 28, 2013
Well... I've not written enough descriptor-implementing code to have a clear opinion on this, but this looks quite obscure. I have personally never needed anything like the wrapt library (I've also never used the PyPI "decorator" module, FWIW).
gvanrossum commentedon Oct 28, 2013
@Grahamd: I occasionally have felt the pain of wrapping @classmethod (or @staticmethod). Never enough though to think of how to fix it. I really don't have the stomach to review your wrapt library, but your code looks okay except for style and missing tests. I'd also recommend adding a few words to the docs. (And yes, all of this is your responsibility -- nobody has time to do all that stuff for you.)
Style-wise:
rhettinger commentedon Oct 30, 2013
Graham, do we have a contributor agreement from you?
grahamd commentedon Oct 30, 2013
I don't believe so.
berkerpeksag commentedon May 5, 2016
Here is an updated patch with a test (adapted from msg198274.)
serhiy-storchaka commentedon May 5, 2016
With the patch class properties work:
This is worth to be explicitly documented.
serhiy-storchaka commentedon Jul 7, 2018
Berker, do you mind to create a PR?
Supporting class properties looks good rationale to me. But we need to check how this change affects performance.
berkerpeksag commentedon Jul 7, 2018
I will submit a PR tomorrow.
Do you have specific ideas for a micro-benchmark in mind or do you want to me just run the Python benchmark suite against the patch?
serhiy-storchaka commentedon Jul 7, 2018
I think it is impossible to get significant impact on the Python benchmark suite from this patch. But mickrobenchmarks can expose the regression if it exists. Something like:
rhettinger commentedon Aug 24, 2019
New changeset 805f8f9 by Raymond Hettinger (Berker Peksag) in branch 'master':
bpo-19072: Make @classmethod support chained decorators (GH-8405)
805f8f9
rhettinger commentedon Oct 24, 2020
New changeset 8e5b0fd by Raymond Hettinger in branch 'master':
bpo-19072: Update descriptor howto for decorator chaining (GH-22934)
8e5b0fd
rhettinger commentedon Oct 24, 2020
New changeset c17f63f by Miss Skeleton (bot) in branch '3.9':
bpo-19072: Update descriptor howto for decorator chaining (GH-22934) (GH-22935)
c17f63f
iritkatriel commentedon Jan 5, 2021
I've created a followup issue re documentation of this change: bpo-42832
ambv commentedon Jul 15, 2021
New changeset b83861f by Łukasz Langa in branch 'main':
bpo-42073: allow classmethod to wrap other classmethod-like descriptors (bpo-27115)
b83861f
ambv commentedon Jul 15, 2021
New changeset 2ce8af3 by Miss Islington (bot) in branch '3.10':
bpo-42073: allow classmethod to wrap other classmethod-like descriptors (GH-27115) (GH-27162)
2ce8af3
ambv commentedon Nov 19, 2021
New changeset e34809e by Raymond Hettinger in branch 'main':
bpo-19072: Classmethod can wrap other classmethod like descriptors (GH-29634)
e34809e
ambv commentedon Nov 19, 2021
New changeset bbe3c57 by Miss Islington (bot) in branch '3.10':
bpo-19072: Classmethod can wrap other classmethod like descriptors (GH-29634) (GH-29643)
bbe3c57