Skip to content

Cannot access class defined type aliases from self or cls [name-defined] #14022

Closed as not planned

Description

@zakstucke

Bug Report

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.

To Reproduce

Gist:
https://mypy-play.net/?mypy=0.981&python=3.10&flags=check-untyped-defs&gist=ee4d1abd57d779210f5bbc6be3cc4dfa

class Test:
    Vector = list[float]

    # MyPy happy with class name access:
    def my_vec_working(self):
        vec: Test.Vector = [1.0, 2.0, 3.0]  # <--- No error
        return vec

    # Mypy errors when accessing with self:
    def my_vec_errors_1(self):
        vec: self.Vector = [1.0, 2.0, 3.0]  # <--- Name "self.Vector" is not defined  [name-defined]
        return vec

    # Mypy errors with cls access in class method:
    @classmethod
    def my_vec_errors_2(cls):
        vec: cls.Vector = [1.0, 2.0, 3.0]  # <--- Name "self.Vector" is not defined  [name-defined]
        return vec

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.

Activity

  1. erictraut commented on Nov 7, 2022

    @erictraut

    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.

  2. erictraut commented on Aug 14, 2023

    @erictraut

    I think mypy is doing the right thing here. Type annotations cannot be dynamic. Recommend closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-aliasTypeAlias and other type alias issues

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions