You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Cannot access class defined type aliases from self or cls[name-defined] #14022
When creating type aliases as class attributes, these attributes can only be accessed using ClassName.VarName, but not self.VarName or cls.VarName in methods and classmethods.
This becomes problematic when class names are long leading to complicated and verbose type annotations.
classTest:
Vector=list[float]
# MyPy happy with class name access:defmy_vec_working(self):
vec: Test.Vector= [1.0, 2.0, 3.0] # <--- No errorreturnvec# Mypy errors when accessing with self:defmy_vec_errors_1(self):
vec: self.Vector= [1.0, 2.0, 3.0] # <--- Name "self.Vector" is not defined [name-defined]returnvec# Mypy errors with cls access in class method:@classmethoddefmy_vec_errors_2(cls):
vec: cls.Vector= [1.0, 2.0, 3.0] # <--- Name "self.Vector" is not defined [name-defined]returnvec
Expected Behavior
Class defined type aliases should be usable as types with self. and cls.
Actual Behavior
error: Name "self.Vector" is not defined [name-defined]
Your Environment
Tested with Python 3.10 and 11, Mypy 0.981 and 0.982.
The use of variables within type annotation expressions is not allowed. In this case, self and cls are variables. As your sample shows, Test.Vector is a legal type annotation, but self.Vector and cls.Vector are not.
Activity
erictraut commentedon Nov 7, 2022
The use of variables within type annotation expressions is not allowed. In this case,
selfandclsare variables. As your sample shows,Test.Vectoris a legal type annotation, butself.Vectorandcls.Vectorare not.erictraut commentedon Aug 14, 2023
I think mypy is doing the right thing here. Type annotations cannot be dynamic. Recommend closing.