1

I tried the following code:

from dataclasses import asdict, dataclass


@dataclass
class DC:
    a: int
    b: int

c = DC(a=10, b=5)
dc = asdict(c)
print(dc)

On Python 3.10 it works as expected, printing a dictionary as expected. When I try the same with Python 3.11 I get the following error:

File "C:\Sources\IAA\python-utils\tests\test_dict.py", line 11, in <module>
    dc = asdict(c)
         ^^^^^^^^^
  File "C:\Python\311\Lib\dataclasses.py", line 1272, in asdict
    if not _is_dataclass_instance(obj):
           ^^^^^^^^^^^^^^^^^^^^^^
NameError: name '_is_dataclass_instance' is not defined. Did you mean: 
'config_is_dataclass_instance'?

I checked the Python 3.11 documentation, dataclasses.asdict is there and should work. Am I doing something wrong, or is this a Python 3.11.1 bug?

The solution for Python 3.11.1 is to add the following lines to my module:

import dataclasses
dataclasses._is_dataclass_instance = dataclasses.config_is_dataclass_instance

But it's really not a good solution.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
zmbq
  • 38,013
  • 14
  • 101
  • 171
  • 1
    `is_data_class_instance` is defined in the source for 3.11 and on the main CPython branch on Github. `config_is_dataclass_instance` is not defined in the source. Are you using the CPython distribution? – snakecharmerb Jan 28 '23 at 17:28
  • Well, this is really confusing and may be a result of some extra characters leaking into it, as @user2357112 suggested. Which is weird since I'm using a virtual environment and I've recreated it from scratch. I will reinstall Python. – zmbq Jan 28 '23 at 17:55

1 Answers1

1

You've corrupted your dataclasses.py somehow, likely with previous edits similar to the one you just made. Trying to restore it manually is far too error-prone. Your best bet at this point is to uninstall and reinstall Python.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • That is unlikely, I'm using a virtual environment, and I've recreated it after seeing this behavior. I'll reinstall Python just to make sure. – zmbq Jan 28 '23 at 17:54
  • Unlikely as it was, that was the correct solution - reinstalling Python 3.11.1 fixed the issue. Next time I should install Python 3.11 in a directory without write access, so I don't do this by mistake. I wonder why recreating the virtual environment didn't fix this. – zmbq Jan 28 '23 at 18:06