Skip to content

Commit a447893

Browse files
committed
Fix crash on incorrect typing.ClassVar annotation
1 parent fbfb76b commit a447893

2 files changed

Lines changed: 23 additions & 2 deletions

File tree

‎src/msgspec/_core.c‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6036,7 +6036,7 @@ structmeta_is_classvar(
60366036
if (temp == NULL) return 0;
60376037
temp = PyObject_GetAttrString(temp, "ClassVar");
60386038
int status = temp == mod->typing_classvar;
6039-
Py_DECREF(temp);
6039+
Py_XDECREF(temp);
60406040
return status;
60416041
}
60426042
}

‎tests/unit/test_struct.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import operator
66
import pickle
77
import sys
8+
import textwrap
89
import weakref
910
from contextlib import contextmanager
1011
from inspect import Parameter, Signature
@@ -2604,11 +2605,31 @@ class Ex(Struct):
26042605
def test_classvar(self, case, future_annotations):
26052606
source = getattr(self, f"case{case}")()
26062607
if future_annotations:
2607-
source = " from __future__ import annotations\n" + source
2608+
source = "from __future__ import annotations\n" + textwrap.dedent(source)
26082609
with temp_module(source) as mod:
26092610
assert mod.Ex.__struct_fields__ == ("a", "b")
2611+
assert not hasattr(mod.Ex, "cv1")
26102612
assert mod.Ex.cv2 == 1
26112613

2614+
def test_wrong_classvar(self):
2615+
# See https://github.com/msgspec/msgspec/issues/1096
2616+
source = """
2617+
from __future__ import annotations
2618+
from msgspec import Struct
2619+
2620+
class typing:
2621+
pass
2622+
2623+
class Ex(Struct):
2624+
a: typing.ClassVar
2625+
"""
2626+
2627+
with pytest.raises(
2628+
AttributeError,
2629+
match="'typing' has no attribute 'ClassVar'",
2630+
):
2631+
temp_module(source).__enter__() # It used to crash, but must not!
2632+
26122633

26132634
class TestPostInit:
26142635
def test_post_init(self):

0 commit comments

Comments
 (0)