From 383290f65dcd209b53357f190cbf2f83ec604b38 Mon Sep 17 00:00:00 2001 From: Hasan Ramezani Date: Fri, 5 Jan 2024 20:08:39 +0330 Subject: [PATCH] Fix module `path_type` creation when globals does not contain `__name__` (#8470) --- pydantic/type_adapter.py | 2 +- tests/test_plugins.py | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/pydantic/type_adapter.py b/pydantic/type_adapter.py index 05e2222e35..feda5d839c 100644 --- a/pydantic/type_adapter.py +++ b/pydantic/type_adapter.py @@ -204,7 +204,7 @@ def __init__( except AttributeError: if module is None: f = sys._getframe(1) - module = cast(str, f.f_globals['__name__']) + module = cast(str, f.f_globals.get('__name__', '')) validator = create_schema_validator( core_schema, type, module, str(type), 'TypeAdapter', core_config, config_wrapper.plugin_settings ) # type: ignore diff --git a/tests/test_plugins.py b/tests/test_plugins.py index 355a8aa46a..f1a15119b5 100644 --- a/tests/test_plugins.py +++ b/tests/test_plugins.py @@ -360,6 +360,28 @@ def new_schema_validator(self, schema, schema_type, schema_type_path, schema_kin TypeAdapter(List[str], module='provided_module_by_type_adapter') +def test_plugin_path_type_adapter_without_name_in_globals() -> None: + class CustomOnValidatePython(ValidatePythonHandlerProtocol): + pass + + class Plugin: + def new_schema_validator(self, schema, schema_type, schema_type_path, schema_kind, config, plugin_settings): + assert str(schema_type) == 'typing.List[str]' + assert schema_type_path == SchemaTypePath('', 'typing.List[str]') + assert schema_kind == 'TypeAdapter' + return CustomOnValidatePython(), None, None + + plugin = Plugin() + with install_plugin(plugin): + code = """ +from typing import List + +import pydantic +pydantic.TypeAdapter(List[str]) +""" + exec(code, {'bar': 'baz'}) + + def test_plugin_path_validate_call() -> None: class CustomOnValidatePython(ValidatePythonHandlerProtocol): pass