beartype: [Bug] @beartype forward reference proxies invoke descriptor `__set_name__()` calls with erroneous owners š©
beartype==0.19.0
Python 3.12.3
Example Code
beartype_test2.py
from functools import wraps
# based on http://stackoverflow.com/questions/2589690/creating-a-method-that-is-simultaneously-an-instance-and-class-method
class combomethod:
def __init__(self, method):
self.method = method
def __get__(self, obj=None, objtype=None):
@wraps(self.method)
def _wrapper(*args, **kwargs):
print("DEBUG:", obj, objtype, args, kwargs)
return self.method(obj if obj is not None else objtype, *args, **kwargs)
return _wrapper
class A:
@combomethod
def f(self_or_cls):
print(self_or_cls)
class B(A):
pass
beartype_test1.py
from beartype.claw import beartype_packages
beartype_packages(("beartype_test2",))
from beartype_test2 import A, B
A.f()
B.f()
B().f()
Running python beartype_test1.py without beartype (comment out beartype_packages):
DEBUG: None <class 'beartype_test2.A'> () {}
<class 'beartype_test2.A'>
DEBUG: None <class 'beartype_test2.B'> () {}
<class 'beartype_test2.B'>
DEBUG: <beartype_test2.B object at 0xfec5786c1a00> <class 'beartype_test2.B'> () {}
<beartype_test2.B object at 0xfec5786c1a00>
Running python beartype_test1.py with beartype active (like in the example code above):
DEBUG: None <class 'beartype_test2.A'> () {}
<class 'beartype_test2.A'>
DEBUG: None <class 'beartype_test2.A'> () {}
<class 'beartype_test2.A'>
DEBUG: None <class 'beartype_test2.A'> (<beartype_test2.A object at 0xe346c16e3ec0>,) {}
Traceback (most recent call last):
File ".../beartype_test1.py", line 9, in <module>
B().f()
File ".../beartype_test2.py", line 13, in _wrapper
return self.method(obj if obj is not None else objtype, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: A.f() takes 1 positional argument but 2 were given
We can see that:
- when calling
B.f()with beartype,fthinks itās being called fromAnotB(without beartypefseesB) -__get__is being passed wrongobjtype, - when calling
B().f()with beartype, the call happening isA.f()(as we can see inTypeErrormessage) andB()is passed through*args-__get__is being passed wrongobjtype(as before) plusobjis missing.
I really like the idea of beartype but when used in one of the projects Iām working on (~250k lines of Django code) it blows up in many places. This is one case I was able to pinpoint. Maybe the others are also based on this error as Django uses quite a lot of descriptors.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 1
- Comments: 16 (9 by maintainers)
Commits related to this issue
- Official descriptor support x 1. This commit is the first in a commit chain adding official support for **descriptors** (i.e., low-level objects satisfying the descriptor protocol by defining the `__... — committed to beartype/beartype by leycec 2 years ago
- Official descriptor support x 2. This commit is the last in a commit chain adding official support for **descriptors** (i.e., low-level objects satisfying the descriptor protocol by defining the `__g... — committed to beartype/beartype by leycec 2 years ago
- Forward reference proxy + `hasattr()`. This commit improves integration between @beartype-specific **forward reference proxies** (i.e., `beartype._check.forward.reference.fwdrefabc.BeartypeForwardRef... — committed to beartype/beartype by leycec 2 years ago
- Forward reference proxy + `hasattr()` x 2. This commit is the last in a commit chain improving integration between @beartype-specific **forward reference proxies** (i.e., `beartype._check.forward.ref... — committed to beartype/beartype by leycec 2 years ago
- Forward reference proxies + `__set_name__()`. This commit resolves a critical (albeit *extremely* subtle) issue at the intersection between **forward reference proxies** (i.e., `beartype._check.forwa... — committed to beartype/beartype by leycec 2 years ago
- Beartype 0.20.0 Release Candidate 2: Bugs Begone **Beartype 0.20.0 Release Candidate 2** is... my Gods. Didn't I just do this two days ago? In hindsight, I should've waited two days. This had better ... — committed to beartype/beartype by leycec 2 years ago
@leycec Iāve found the problem!
So, this code:
takes us here:
We are not passing
type_scopeso itāsNoneand then:So letās check
DICT_EMPTY:Thatās far from empty! š
So letās look at
beartype._data.kind.datakinddict.DICT_EMPTY:Thatās a global mutable dict!
So, what to do? For a quick and dirty fix I just changed everywhere in @beartype code
DICT_EMPTYā”DICT_EMPTY.copy()and my example works! š For a nicer solutionDICT_EMPTYcould be turned into a function returning an empty dict.Also, this looks potentially bad (although works with my example): beartype/door/_func/infer/collection/infercollectionsab.py:_FiniteStateMachineNode
An argumentās default value that is mutable is probably a bad idea š
One potential problem with this solution is that you could be, without realizing it, depending somewhere on
DICT_EMPTYnot being empty so I leave the dirty work to you š¼This time itās not CPythonās fault š
The tip about PEP 563 gave me an idea and I seems the problem was me trying to avoid workā¦
I wanted to quickly check if using @beartype for my project makes sense and it was raising a lot of errors about forward references that the bear couldnāt resolve. Instead of rewriting the type hints to use fully qualified class names and changing
if TYPE_CHECKINGimports I decided to change @beartype code (that was too cocky of meā¦).I changed
beartype/_check/forward/reference/fwdrefmeta.py:BeartypeForwardRefMeta.__instancecheck__to catchBeartypeCallHintForwardRefExceptionandreturn True. The idea was āif you canāt resolve a forward reference to type check something, assume everything is fineā. This seemed to work when the executing code wasnāt touching my weird descriptors using__set_name__.Whatās doubly weird (or triply or Iāve lost countā¦) is that to fix the
__set_name__issue I had to rewrite type annotations in only one file! For everything else suppressingBeartypeCallHintForwardRefExceptionstill works.Why? Who knows. The bearās cave is too complex to explore with the current spelunking technology.
Thank you for the help, @leycec . The bear has earned a permanent seat at the table of my development workflow š„³
Thank you, @leycec ! Youāre awesome! These 2 commits seem to fix this issue. Itās not a problem that descriptors wonāt be type-checked. Itās enough that they donāt blow up š
I found another bug⦠This time with
descriptor.__set_name__if you are saving theownerargument for future use. If descriptors are black magic, then this is vantablack magic so I think it can be ignored š Also, I couldnāt create a simple example for the bug. I even tried creating a small Django project from scratch but everything worked (one time I would prefer things to not workā¦).Iāll just leave a short description of the results of my hoooours-long investigation for future generations of @beartype users.
Normally
__set_name__is passedowner=<class where descriptor instance was used>but in some weird case (which is unfortunately my case), when defined on a DjangoModeland @beartype is active,__set_name__will be first called withowner=<class my_app.models.MyModel>(which is good) and then will be called withowner=<forwardref MyOtherModel(__name_beartype__=None, __scope_name_beartype__=None)>once for everyModelwhich is used anywhere in my project in any type annotation. Each call has the samenameargument (which means it doesnāt interfere withdjango.utils.functional.cached_property) so the problem is only if you are saving theownerargument as descriptor instance attribute and using it later (which I do in one of my descriptor use cases). Fortunately, workaround is easy. Just ignore all__set_name__calls after the first one.The first, expected stack trace (all models use a custom metaclass that inherits from Djangoās regular Model metaclass):
Other, long and weird stack traces:
Everything seems to be working on my codebase now š Thank you, @leycec ! š
Resolved by 3f18100213f9a8e⦠uhh, maybe. Itās best to assume nothing with this issue, which shall hereafter be referred to as āThe Neverending Issue.ā Iām tired, my face is numb, and Iām all of out luck dragons.
Would you mind giving this a final try? Your Django use case is the ultimate torture test. And I do emphasize ātorture.ā Pretty sure we both now need to seek psychotherapy on a couch:
Thanks again for your phenomenal efforts with this @beartype beast, @rudimichal! Youāve gone above and beyond the call of Pythonic QA. Truly, a magical miracle happened here tonight.
Glad I could be of help š
This should make @beartype faster. Now forward reference proxies will be just simple classes with appropriate base class and no attributes as opposed to thousands of random attributes gathered by
DICT_EMPTYthroughout a large codebase such as mine. Potentially, it could have also been messing with Python garbage collecting as forward reference proxies were hanging on to random objects.YAAAAAAAAAAY! Thanks so much for deciphering our unabashed failures, @rudimichal. It⦠was totally our fault after all. @beartype has fallen down and cannot get up.
Now that youāve done all the heavy and painful lifting that cost you your very will to live, this should be trivial. Iāll stumble onwards and upwards from here by:
DICT_EMPTYimplementation with @beartypeās own emptyFrozenDictimplementation: e.g.,DICT_EMPTYentirely from the codebase. Itās just too risky to have xenomorph face-hugger like that hanging around.Looks like thereās gonna be a @beartype
0.20.0rc2after all. Sadness becomes me. šUrgh! This⦠is⦠so⦠horrible. Thereās so much arcane black low-level magic going here I can barely see straight. Descriptors make my eyes bleed. I canāt be the only one, people! š
In all likelihood, this has been an unresolved @beartype issue for literally a decade. Nobody knew. Apparently, nobody uses descriptors ā including myself. Iām genuinely surprised, because descriptors are so insanely useful in theory. In practice, they scare everybody.
This is now my immediate priority. The good news is that Iāve resolved this exact issue locally. The bad news is that Iām not entirely confident that I know what Iām doing or that this resolution scales to all possible edge cases (e.g., descriptors with type hints). And⦠there goes our upcoming @beartype
0.20.0release window. Itās gone. The window has closed.Thanks so much for this detailed issue, @rudimichal. Youāre stunning! The Django apps youāre building out must be equally stunning. Someday, @beartype will join you in that journey.