Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion mypyc/irbuild/classdef.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,16 @@ def add_non_ext_class_attr_ann(
if get_type_info is not None:
type_info = get_type_info(stmt)
if type_info:
typ = load_type(builder, type_info, stmt.line)
# NOTE: Using string type information is similar to using
# `from __future__ import annotations` in standard python.
# NOTE: For string types we need to use the fullname since it
# includes the module. If string type doesn't have the module,
# @dataclass will try to get the current module and fail since the
# current module is not in sys.modules.
if builder.current_module == type_info.module_name and stmt.line < type_info.line:
typ = builder.load_str(type_info.fullname)
else:
typ = load_type(builder, type_info, stmt.line)

if typ is None:
# FIXME: if get_type_info is not provided, don't fall back to stmt.type?
Expand Down
29 changes: 29 additions & 0 deletions mypyc/test-data/run-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -2719,3 +2719,32 @@ print(native.A(ints=[1, -17]).ints)

[out]
\[1, -17]

[case testDataclassClassReference]
from __future__ import annotations
from dataclasses import dataclass

class BackwardDefinedClass:
pass

@dataclass
class Data:
bitem: BackwardDefinedClass
bitems: 'BackwardDefinedClass'
fitem: ForwardDefinedClass
fitems: 'ForwardDefinedClass'

class ForwardDefinedClass:
pass

def test_function():
d = Data(
bitem=BackwardDefinedClass(),
bitems=BackwardDefinedClass(),
fitem=ForwardDefinedClass(),
fitems=ForwardDefinedClass(),
)
assert(isinstance(d.bitem, BackwardDefinedClass))
assert(isinstance(d.bitems, BackwardDefinedClass))
assert(isinstance(d.fitem, ForwardDefinedClass))
assert(isinstance(d.fitems, ForwardDefinedClass))