annotations cause dataclass fields type side effects

Barry barry at barrys-emacs.org
Tue Aug 10 17:00:14 EDT 2021



> On 9 Aug 2021, at 19:28, Lukas Lösche <lukas at some.engineering> wrote:
> 
> I'm on Python 3.9.6 and trying to make sense of the following behaviour:
> 
>>>> from dataclasses import dataclass, fields
>>>> @dataclass
> ... class Foobar:
> ... name: str
> ...
>>>> fields(Foobar)[0].type
> <class 'str'>
>>>> type(fields(Foobar)[0].type)
> <class 'type'>
> 
> 
> 
>>>> from __future__ import annotations
>>>> from dataclasses import dataclass, fields
>>>> 
>>>> @dataclass
> ... class Foobar:
> ... name: str
> ...
>>>> fields(Foobar)[0].type
> 'str'
>>>> type(fields(Foobar)[0].type)
> <class 'str'>
> 
> I have a validation function that checks if the types of all fields in
> a dataclass are what they are supposed to be. But as soon as I import
> annotations from __future__ this validation breaks as the arg that I'm
> passing to isinstance() is no longer a type class but a string.
> 
> What am I doing wrong?

Nothing.

As I understand the current situation you have to check if it’s a string and convert to the object you need at the moment. Hopefully someone with a deeper understanding will
explain how you do this. I would guess use eval.

This is a known problem and there are core devs that are working on improvements.
But it will be at leas python 3.11 before there is a possible improvement.

Barry

> 
> Thanks,
> -- Lukas
> -- 
> https://mail.python.org/mailman/listinfo/python-list
> 



More information about the Python-list mailing list