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, f thinks it’s being called from A not B (without beartype f sees B) - __get__ is being passed wrong objtype,
  • when calling B().f() with beartype, the call happening is A.f() (as we can see in TypeError message) and B() is passed through *args - __get__ is being passed wrong objtype (as before) plus obj is 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

Most upvoted comments

@leycec I’ve found the problem!

So, this code:

# Forward reference proxy to be returned.
    forwardref_subtype = make_type(
        type_name=type_name,
        type_module_name=type_module_name,
        type_bases=type_bases,
        exception_cls=BeartypeDecorHintForwardRefException,
        exception_prefix='Forward reference ',
    )

takes us here:

def make_type(
    # Mandatory arguments.
    type_name: str,

    # Optional arguments.
    type_module_name: Optional[str] = None,
    type_bases: Optional[TupleTypes] = None,
    type_scope: Optional[LexicalScope] = None,
    type_doc: Optional[str] = None,
    exception_cls: TypeException = _BeartypeUtilTypeException,
    exception_prefix: str = '',
) -> type:
    ...

We are not passing type_scope so it’s None and then:

if type_scope is None:
        type_scope = DICT_EMPTY  # type: ignore[assignment]

So let’s check DICT_EMPTY:

(Pdb) !DICT_EMPTY
{'A': <class 'beartype_a.A'>, '__module__': 'beartype_a', 'prop': <beartype_a.cached_property object at 0xeb5b638e2a20>, 'f': <function A.f at 0xeb5b637bfa60>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}

That’s far from empty! 😁

So let’s look at beartype._data.kind.datakinddict.DICT_EMPTY:

DICT_EMPTY: Dict[Any, Any] = {}

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 solution DICT_EMPTY could 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

    def __init__(
        self,

        # Optional parameters.
        hint_factory: object = None,
        nodes_next: _FiniteStateMachine = DICT_EMPTY,
    ) -> None:
        ...

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_EMPTY not 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_CHECKING imports I decided to change @beartype code (that was too cocky of me…).

I changed beartype/_check/forward/reference/fwdrefmeta.py:BeartypeForwardRefMeta.__instancecheck__ to catch BeartypeCallHintForwardRefException and return 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 suppressing BeartypeCallHintForwardRefException still 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 the owner argument 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 passed owner=<class where descriptor instance was used> but in some weird case (which is unfortunately my case), when defined on a Django Model and @beartype is active, __set_name__ will be first called with owner=<class my_app.models.MyModel> (which is good) and then will be called with owner=<forwardref MyOtherModel(__name_beartype__=None, __scope_name_beartype__=None)> once for every Model which is used anywhere in my project in any type annotation. Each call has the same name argument (which means it doesn’t interfere with django.utils.functional.cached_property) so the problem is only if you are saving the owner argument 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):

  File ".../project/login/models.py", line 41, in <module>
    class LoginAttempt(MyBaseModel):
  File ".../project/queryable_properties/models.py", line 17, in __new__
    new_class = super().__new__(cls, name, bases, attrs, **kwargs)
  File ".../lib/python3.12/site-packages/django/db/models/base.py", line 120, in __new__
    new_class = super_new(cls, name, bases, new_attrs, **kwargs)
  File ".../lib/python3.12/site-packages/django/utils/functional.py", line 32, in __set_name__
    if self.name is None:

Other, long and weird stack traces:

  File ".../project/login/models.py", line 41, in <module>
    class LoginAttempt(MyBaseModel):
  File ".../lib/python3.12/site-packages/beartype/_decor/decorcache.py", line 127, in beartype_confed
    return beartype_object(obj, conf)
  File ".../lib/python3.12/site-packages/beartype/_decor/decorcore.py", line 95, in beartype_object
    _beartype_object_nonfatal(obj, conf=conf, **kwargs)
  File ".../lib/python3.12/site-packages/beartype/_decor/decorcore.py", line 215, in _beartype_object_nonfatal
    return _beartype_object_fatal(obj, conf=conf, **kwargs)
  File ".../lib/python3.12/site-packages/beartype/_decor/decorcore.py", line 133, in _beartype_object_fatal
    beartype_type(obj, **kwargs)  # type: ignore[return-value]
  File ".../lib/python3.12/site-packages/beartype/_decor/_decortype.py", line 224, in beartype_type
    attr_value_beartyped = beartype_object(  # type: ignore[type-var]
  File ".../lib/python3.12/site-packages/beartype/_decor/decorcore.py", line 95, in beartype_object
    _beartype_object_nonfatal(obj, conf=conf, **kwargs)
  File ".../lib/python3.12/site-packages/beartype/_decor/decorcore.py", line 215, in _beartype_object_nonfatal
    return _beartype_object_fatal(obj, conf=conf, **kwargs)
  File ".../lib/python3.12/site-packages/beartype/_decor/decorcore.py", line 137, in _beartype_object_fatal
    beartype_nontype(obj, **kwargs)  # type: ignore[return-value]
  File ".../lib/python3.12/site-packages/beartype/_decor/_decornontype.py", line 163, in beartype_nontype
    return beartype_decorator(obj, **kwargs)  # type: ignore[return-value]
  File ".../lib/python3.12/site-packages/beartype/_decor/_decornontype.py", line 602, in _beartype_descriptor_decorator_builtin_class_or_s
tatic_method
    descriptor_wrappee_checked = beartype_object(descriptor_wrappee, **kwargs) # type: ignore[union-attr]
  File ".../lib/python3.12/site-packages/beartype/_decor/decorcore.py", line 95, in beartype_object
    _beartype_object_nonfatal(obj, conf=conf, **kwargs)
  File ".../lib/python3.12/site-packages/beartype/_decor/decorcore.py", line 215, in _beartype_object_nonfatal
    return _beartype_object_fatal(obj, conf=conf, **kwargs)
  File ".../lib/python3.12/site-packages/beartype/_decor/decorcore.py", line 137, in _beartype_object_fatal
    beartype_nontype(obj, **kwargs)  # type: ignore[return-value]
  File ".../lib/python3.12/site-packages/beartype/_decor/_decornontype.py", line 249, in beartype_nontype
    return beartype_func(obj, **kwargs)  # type: ignore[return-value]
  File ".../lib/python3.12/site-packages/beartype/_decor/_decornontype.py", line 336, in beartype_func
    func_wrapper_code = generate_code(decor_meta)
  File ".../lib/python3.12/site-packages/beartype/_decor/wrap/wrapmain.py", line 126, in generate_code
    code_check_return = _code_check_return(decor_meta)
  File ".../lib/python3.12/site-packages/beartype/_decor/wrap/_wrapreturn.py", line 199, in code_check_return
    code_return_check = unmemoize_func_wrapper_code(
  File ".../lib/python3.12/site-packages/beartype/_decor/wrap/_wraputil.py", line 114, in unmemoize_func_wrapper_code
    ref_expr = add_func_scope_ref(
  File ".../lib/python3.12/site-packages/beartype/_check/code/codescope.py", line 135, in add_func_scope_ref
    hint_ref = make_forwardref_indexable_subtype(ref_module_name, ref_name)
  File ".../lib/python3.12/site-packages/beartype/_check/forward/reference/fwdrefmake.py", line 91, in make_forwardref_indexable_subtype
    return _make_forwardref_subtype(  # type: ignore[return-value]
  File ".../lib/python3.12/site-packages/beartype/_check/forward/reference/fwdrefmake.py", line 186, in _make_forwardref_subtype
    forwardref_subtype = make_type(
  File ".../lib/python3.12/site-packages/beartype/_util/cls/utilclsmake.py", line 112, in make_type
    cls = type(type_name, type_bases, type_scope)
  File ".../lib/python3.12/site-packages/django/utils/functional.py", line 32, in __set_name__
    if self.name is None:

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:

pip install git+https://github.com/beartype/beartype.git@3f18100213f9a8e396d2ae7d204461df7ecea610

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.

would you trust a face that looks like this? @leycec would

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_EMPTY throughout 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.

the story of @beartype: ā€œIt’s sad.ā€

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:

  1. Swapping out that clearly awful DICT_EMPTY implementation with @beartype’s own empty FrozenDict implementation: e.g.,
# Everywhere we do something awful like this...
type_scope = DICT_EMPTY

# ...we need to instead do something glorious like this!
from beartype._data.kind.datakinddict import DICT_EMPTY
type_scope = FROZEN_DICT_EMPTY
  1. Probably removing DICT_EMPTY entirely 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.0rc2 after 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.0 release 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.