facebookincubator / cinder

Cinder is Meta's internal performance-oriented production version of CPython.
https://trycinder.com
Other
3.49k stars 121 forks source link

Accessing undeclared field does not raise a type error #51

Open LuKuangChen opened 2 years ago

LuKuangChen commented 2 years ago

6862bbd 2021-10-13

What program did you run?

# lookup_self_field_neg.py
# This should fail.

class C:
    pass

def f(c: C):
    # reveal_type(c.x) # dynamic
    return c.x

What happened?

The program passes type checks.

What should have happened?

We expected a compile-time error complaining that "C has no attribute x". (This is what mypy does.)

Is this another case where Static Python falls back to dynamic (similar to #50)?

carljm commented 2 years ago

Yes, this is a case where we intentionally fall back to dynamic. The problem with strictly enforcing attributes is that we'd kind of like to be able to support cases where people are doing more dynamic things in building their class that our compiler doesn't necessarily understand (e.g. tacking on extra methods after the fact or via dynamic code in the class body, using class decorators that return the same type but maybe tack on extra stuff, maybe soon even some metaclasses); there's not much advantage to us in rejecting stuff like this (makes adoption harder) when we can just as easily fall back to dynamic and allow them to succeed or fail at runtime. Does it cause a problem for you?

I could potentially envision a stricter mode where we would enforce only using attributes that the compiler knows about; it's certainly not hard to implement. I think the ideal behavior here really depends somewhat on whether you are writing new code or trying to convert and gain whatever benefits you can in an existing dynamic codebase.

LuKuangChen commented 2 years ago

Understandable. This is not a problem for us. We just wanted to know if this fall-back-to-dynamic behavior is intended.