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
While working on #2088 I came across an interesting problem. Take this code
class A:
x: int
y: ClassVar[int] = 67
z = 67
It's clear that x is an instance variable and y is a class variable. However z is a bit vague. Technically, as far as python is concerned it's a class variable. Both dataclasses and attr.s(auto_attribs=True) will ignore z when creating the __init__. (Because they only look in cls.__annotations__) (Full disclosure, I haven't run dataclasses yet but looking at the code it looks that way) However I can't figure out a way to tell the difference in mypy code.
Basically I'm walking the class body looking for AssignmentStmts. And I thought "Oh hey. node.is_classvar" should help me here. It return False for x, True for y, but sadly it also returns False for z. To make it harder, if you look at visit_assignment_stmt it does analyze_simple_literal_type to infer the type of z and then store_declared_types sets is_inferred_def = False so I can't tell apart z = 67 from z: int = 67
The text was updated successfully, but these errors were encountered:
euresti
changed the title
classvar ambiguities
Can't tell apart untyped from typed class variable assignment
Dec 19, 2017
I think PEP 526 is clear on this, everything that is not typed with ClassVar is an instance variable. In particular:
classC:
z=42
introduces an instance variable with a default value. As for how to check this in mypy, there are several options and the simplest one is probably to re-use stmt.new_syntax, see semanal.check_namedtuple_classdef.
While working on #2088 I came across an interesting problem. Take this code
It's clear that
x
is an instance variable andy
is a class variable. Howeverz
is a bit vague. Technically, as far as python is concerned it's a class variable. Both dataclasses andattr.s(auto_attribs=True)
will ignorez
when creating the__init__
. (Because they only look incls.__annotations__
) (Full disclosure, I haven't run dataclasses yet but looking at the code it looks that way) However I can't figure out a way to tell the difference in mypy code.Basically I'm walking the class body looking for
AssignmentStmt
s. And I thought "Oh hey. node.is_classvar" should help me here. It return False forx
, True fory
, but sadly it also returns False forz
. To make it harder, if you look atvisit_assignment_stmt
it doesanalyze_simple_literal_type
to infer the type ofz
and thenstore_declared_types
setsis_inferred_def = False
so I can't tell apartz = 67
fromz: int = 67
The text was updated successfully, but these errors were encountered: