Skip to content

BaseSettings descendants call default_factory on import #2515

@pomo-mondreganto

Description

@pomo-mondreganto

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

When importing BaseSettings descendant from another file, default_factory functors are always called for uninstantiated models. See the code snippet attached below. def factory() is called once on import, even though B is not even instantiated.

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

             pydantic version: 1.8.1
            pydantic compiled: True
                 install path: /usr/local/anaconda3/envs/dirty_3.9/lib/python3.9/site-packages/pydantic
               python version: 3.9.2 | packaged by conda-forge | (default, Feb 21 2021, 05:02:20)  [Clang 11.0.1 ]
                     platform: macOS-11.1-x86_64-i386-64bit
     optional deps. installed: ['typing-extensions']

The first file (kek.py):

from pydantic import BaseSettings, Field

v = 0

def factory():
    print('factory called')
    global v
    v += 1
    return v


class A(BaseSettings):
    pass


class B(A):
    id: int = Field(default_factory=factory)

        
class C(A):
    pass

The second file:

from kek import C

Expected output: empty.

Actual output: factory called.

It's also worth mentioning that BaseModel does not have the described behavior, importing the BaseModel descendants doesn't call default_factory functors.

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