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

Model signatures contain reserved words. #4011

3 tasks done
strue36 opened this issue Apr 25, 2022 · 0 comments · Fixed by #4012
3 tasks done

Model signatures contain reserved words. #4011

strue36 opened this issue Apr 25, 2022 · 0 comments · Fixed by #4012
bug V1 Bug related to Pydantic V1.X


Copy link

strue36 commented Apr 25, 2022


  • 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


When creating a model with a field that has an alias that is a python reserved word, the signature uses the reserved word even when allow_population_by_field_name is true.

I expect the signature to use the field name in this case. I came across this issue when generating tests using hypothesis. This uses the model signature and was creating invalid test code as it was using the reserved words in the signature.

pydantic version: 1.9.0
pydantic compiled: False
python version: 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)]
platform: Windows-10-10.0.19041-SP0
optional deps. installed: ['devtools', 'dotenv', 'email-validator', 'typing-extensions']
from pydantic import BaseModel, Field
from inspect import signature

class Foo(BaseModel):
    from_: str = Field(..., alias='from')

    class Config:
        allow_population_by_field_name = True


'(*, from: str) -> None'


In utils.generate_model_signature() we have these two checks.

elif not param_name.isidentifier():
    if allow_names and field_name.isidentifier():

I propose replacing these with calls to the following (new) function.

def is_valid_identifier(identifier: str) -> bool:
    Checks that a string is a valid identifier and not a reserved word.
    :param identifier: The identifier to test.
    :return: True if the identifier is valid.
    return identifier.isidentifier() and not keyword.iskeyword(identifier)

I believe that this behaviour is closer to what a user would expect in the common case that they are generating models from a schema containing python reserved words.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
bug V1 Bug related to Pydantic V1.X
None yet

Successfully merging a pull request may close this issue.

1 participant