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

Fix module path_type creation when globals does not contain __name__ #8470

Merged
merged 1 commit into from Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion pydantic/type_adapter.py
Expand Up @@ -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__', ''))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to default to '__main__' instead of ''?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm, not sure. @samuelcolvin do you have any opinion here?

validator = create_schema_validator(
core_schema, type, module, str(type), 'TypeAdapter', core_config, config_wrapper.plugin_settings
) # type: ignore
Expand Down
22 changes: 22 additions & 0 deletions tests/test_plugins.py
Expand Up @@ -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
Expand Down