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: adding a check that alias is validated as an identifier for Python #7319

Merged

Conversation

andree0
Copy link
Contributor

@andree0 andree0 commented Sep 3, 2023

Change Summary

Changes in generate_dataclass_signature function. I used is_valid_identifier function from _utils.py for alias and validation_alias as new statement when name parameter is replaced by the alias or the validation alias.

I didn't want to use := (walrus operator) in if statement because it isn't support for Python 3.7, so I assigned variables first to make the code more readable.

Related issue number

Fix: #7226

Checklist

  • The pull request title is a good summary of the changes - it will be used in the changelog
  • Unit tests for the changes exist
  • Tests pass on CI
  • Documentation reflects the changes where applicable
  • My PR is ready to review, please add a comment including the phrase "please review" to assign reviewers

@andree0
Copy link
Contributor Author

andree0 commented Sep 3, 2023

Works the same way as BaseModel. We don't get a ValueError that the alias with dash is not a valid parameter name but if We are creating an instance, We get ValidationError that the field is required. I don't know that this is desired effect.

Python 3.11.5 (main, Aug 29 2023, 19:27:22) [GCC 11.4.0]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.15.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from pydantic import BaseModel, Field
   ...: from pydantic.dataclasses import dataclass
   ...: 
   ...: 
   ...: class Example1(BaseModel):
   ...:     some_var: str = Field(..., alias="some-var")
   ...: 
   ...: 
   ...: 
   ...: @dataclass(frozen=True)
   ...: class Example2:
   ...:     some_other_var: str = Field(..., alias="some-other-var")
   ...: 

In [2]: e1 = Example1(some_var="aaa")
---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
Cell In[2], line 1
----> 1 e1 = Example1(some_var="aaa")

File ~/OWN-PROJECTS/pydantic/pydantic/main.py:165, in BaseModel.__init__(__pydantic_self__, **data)
    163 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    164 __tracebackhide__ = True
--> 165 __pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__)

ValidationError: 1 validation error for Example1
some-var
  Field required [type=missing, input_value={'some_var': 'aaa'}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.3/v/missing

In [3]: e2 = Example2(some_other_var="aaa")
---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
Cell In[3], line 1
----> 1 e2 = Example2(some_other_var="aaa")

File ~/OWN-PROJECTS/pydantic/pydantic/_internal/_dataclasses.py:125, in complete_dataclass.<locals>.__init__(__dataclass_self__, *args, **kwargs)
    123 __tracebackhide__ = True
    124 s = __dataclass_self__
--> 125 s.__pydantic_validator__.validate_python(ArgsKwargs(args, kwargs), self_instance=s)

ValidationError: 1 validation error for Example2
some-other-var
  Field required [type=missing, input_value=ArgsKwargs((), {'some_other_var': 'aaa'}), input_type=ArgsKwargs]
    For further information visit https://errors.pydantic.dev/2.3/v/missing

@andree0
Copy link
Contributor Author

andree0 commented Sep 3, 2023

In [2]: Example1(**{"some-var": "aaa"})
Out[2]: Example1(some_var='aaa')

In [3]: Example2(**{"some-other-var": "aaa"})
Out[3]: Example2(some_other_var='aaa')

In [4]: Example1.model_validate({"some-var": "aaa"})
Out[4]: Example1(some_var='aaa')

tests/test_dataclasses.py Outdated Show resolved Hide resolved
tests/test_dataclasses.py Outdated Show resolved Hide resolved
@hramezani
Copy link
Member

Thanks @andree0 for this patch 🙏

I left some comments. please update

tests/test_dataclasses.py Outdated Show resolved Hide resolved
tests/test_dataclasses.py Outdated Show resolved Hide resolved
@hramezani hramezani enabled auto-merge (squash) September 4, 2023 20:51
@hramezani hramezani merged commit 99555e9 into pydantic:main Sep 4, 2023
46 checks passed
@andree0 andree0 deleted the b/alias-with-dashes-in-dataclasses/7226 branch September 4, 2023 21:22
@davidhewitt davidhewitt added the relnotes-fix Used for bugfixes. label Sep 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Field alias does not accept parameter name with dashes in pydantic dataclasses
3 participants