0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】PydanticUserErrorの原因は、モジュールをフィールドとして誤認識していたためだった...

Posted at

概要

FastAPIのアプリをAWS Lambdaで動かそうとしたら以下のエラーが発生しました。
解決方法を紹介します。

[ERROR] PydanticUserError: A non-annotated attribute was detected: os = <module 'os' (frozen)>. All model fields require a type annotation; if os is not meant to be a field, you may be able to resolve this error by annotating it as a ClassVar or updating model_config['ignored_types'].

解決方法

エラーメッセージから察するに、Pydantic(=データモデルの定義とバリデーションを簡単に行うためのツール)がクラスの属性としてosモジュールを誤って認識してしまっているのが原因。

具体的には、以下のように、2回モジュールをインポートしてしまっていました。

import os
from pydantic import BaseModel

class MyModel(BaseModel):
    import os  # これが原因でエラーが発生する

    name: str
    age: int

この場合、Pydanticがosモジュールをフィールドとして誤認識し、型注釈がないためエラーが発生していたのだと思われます。

import osを1回だけにしたらエラーは無くなりました!

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?