Skip to content

NamedTuple doesn't resolve postponed annotations #2760

@jameysharp

Description

@jameysharp

Checks

  • I added a descriptive title to this issue
  • I have searched (google, github) for similar issues and couldn't find anything
  • I have read and followed the docs and still think this is a bug

Bug

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.8.1
            pydantic compiled: False
                 install path: /nix/store/1f6nk37c7df54cm8b3rlnn6pidaa3mrp-python3.8-pydantic-1.8.1/lib/python3.8/site-packages/pydantic
               python version: 3.8.8 (default, Feb 19 2021, 11:04:50)  [GCC 9.3.0]
                     platform: Linux-5.4.114-x86_64-with
     optional deps. installed: ['typing-extensions']

Here's the smallest program I could come up with that fails under from __future__ import annotations but works without it:

from __future__ import annotations

from pydantic import BaseModel, PositiveInt
from typing import NamedTuple

class Tup(NamedTuple):
    v: PositiveInt

class Mod(BaseModel):
    t: Tup

print(Mod.parse_obj({"t": [3]}))

The call to parse_obj raises this exception: pydantic.errors.ConfigError: field "v" not yet prepared so type is still a ForwardRef, you might need to call Tup.update_forward_refs(). But there is no update_forward_refs on NamedTuple instances.

Just using a base int in the NamedTuple doesn't exhibit the same problem, but of course it also doesn't check the constraints I want.

My current workaround is to just not use from __future__ import annotations in the module where I declare and use the NamedTuple, but I was hoping to use the new style consistently throughout the project.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V1Bug related to Pydantic V1.X

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions