Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Running pydantic type validation in generated code string raises KeyError: '__name__' #8448

Closed
1 task done
KhoomeiK opened this issue Dec 29, 2023 · 1 comment · Fixed by #8470
Closed
1 task done
Assignees
Labels
bug V2 Bug related to Pydantic V2

Comments

@KhoomeiK
Copy link

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

When running type validation of non-pydantic_validator objects in a string execution (e.g. generated code) context, a KeyError: '__name__' is raised by TypeAdapter.__init__ unless {'__name__': '__main__'} is passed as part of global variables to exec.

While this issue is trivial to fix for a user if they understand the execution context requirements, it seems this __name__ requirement was only recently added to the type adapter and the raised error is fairly confusing and/or unexpected behavior.

Traceback (most recent call last):
  File "python3.11/site-packages/pydantic/type_adapter.py", line 197, in __init__
    validator = _getattr_no_parents(type, '__pydantic_validator__')
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "python3.11/site-packages/pydantic/type_adapter.py", line 98, in _getattr_no_parents
    raise AttributeError(attribute)
AttributeError: __pydantic_validator__

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 2, in <module>
  File "python3.11/site-packages/pydantic/type_adapter.py", line 201, in __init__
    module = cast(str, f.f_globals['__name__'])
                       ~~~~~~~~~~~^^^^^^^^^^^^
KeyError: '__name__'

The simplest fix here in my mind is to check if __name__ is present on f.f_globals and if not, either raise a more informative error or set it to __main__ by default.

Example Code

code = """import pydantic
pydantic.TypeAdapter(str).validate_python('foo')"""

exec(code, {"bar": "baz"})

# USER FIX:
exec(code, {"bar": "baz", '__name__': '__main__'})

Python, Pydantic & OS Version

pydantic version: 2.5.2
        pydantic-core version: 2.14.5
          pydantic-core build: profile=release pgo=true
                 install path: /Users/rohan/Library/Caches/pypoetry/virtualenvs/deworker-TwLL-mi8-py3.11/lib/python3.11/site-packages/pydantic
               python version: 3.11.6 (main, Nov  2 2023, 04:39:43) [Clang 14.0.3 (clang-1403.0.22.14.1)]
                     platform: macOS-13.3-arm64-arm-64bit
             related packages: typing_extensions-4.9.0 mypy-1.7.1 pydantic-settings-2.1.0
@KhoomeiK KhoomeiK added bug V2 Bug related to Pydantic V2 pending Awaiting a response / confirmation labels Dec 29, 2023
@hramezani
Copy link
Member

Thanks @KhoomeiK for reporting this.

It can be fix by passing module to TypeAdapter.

pydantic.TypeAdapter(str, module='my_module').validate_python('foo')

BTW, I've created #8470 for fixing the bug

@hramezani hramezani removed the pending Awaiting a response / confirmation label Jan 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug V2 Bug related to Pydantic V2
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants