Skip to content

Commit

Permalink
Merge pull request #344 from sanders41/pydantic-2
Browse files Browse the repository at this point in the history
Make compatable with Pydantic 2
  • Loading branch information
sanders41 authored Jul 1, 2023
2 parents ac30b2f + b492189 commit 1dc7a53
Show file tree
Hide file tree
Showing 3 changed files with 247 additions and 139 deletions.
21 changes: 16 additions & 5 deletions camel_converter/pydantic_base.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
try:
from pydantic import BaseModel # type: ignore
import pydantic # type: ignore
except ImportError:
raise ImportError("camel-converter must be installed with the pydantic extra to use this class")

from camel_converter import to_camel


class CamelBase(BaseModel):
class CamelBase(pydantic.BaseModel):
"""A Pydantic model that provides a base configuration for conveting between camel and snake case.
If another Pydantic model inherit from this class it will get the ability to do this conversion
between camel and snake case without having to add the configuration to the new model.
"""

class Config:
alias_generator = to_camel
allow_population_by_field_name = True
try:
# __version__ was added with Pydantic 2 so we know if this errors the version is < 2.
# Still check the version as a fail safe incase __version__ gets added to verion 1.
if int(pydantic.__version__[:1]) >= 2: # type: ignore[attr-defined]
model_config = pydantic.ConfigDict(alias_generator=to_camel, populate_by_name=True) # type: ignore[attr-defined]
else: # pragma: no cover
# Raise an AttributeError to match the AttributeError on __version__ because in either
# case we need to get to the same place.
raise AttributeError
except AttributeError: # pragma: no cover

class Config:
alias_generator = to_camel
allow_population_by_field_name = True
Loading

0 comments on commit 1dc7a53

Please sign in to comment.