Skip to content

Commit

Permalink
Fixed imports to avoid pydantic if the version is >=2
Browse files Browse the repository at this point in the history
  • Loading branch information
evalott100 committed Jul 5, 2023
1 parent 34a4eb6 commit a65379b
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 6 deletions.
24 changes: 21 additions & 3 deletions event_model/documents/generate/type_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,39 @@
"""


import pkgutil
from dataclasses import dataclass

try:
import pydantic
pydantic_path = pkgutil.find_loader("pydantic")
pydantic_version = None
if pydantic_path:
import pydantic # type: ignore

pydantic_version = pydantic.__version__

if pydantic_version and int(pydantic_version.split(".")[0]) < 2:
Field = pydantic.Field
FieldInfo = pydantic.fields.FieldInfo
except ModuleNotFoundError:
BaseConfig = pydantic.BaseConfig
BaseModel = pydantic.BaseModel
create_model = pydantic.create_model
else:

def Field(*args, **kwargs): # type: ignore
...

class FieldInfo: # type: ignore
...

class BaseConfig: # type: ignore
...

class BaseModel: # type: ignore
...

def create_model(*args, **kwargs): # type: ignore
...


extra_schema = {}

Expand Down
17 changes: 15 additions & 2 deletions event_model/documents/generate/typeddict_to_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
from pathlib import Path
from typing import Dict, Optional, Tuple, Type, Union

from pydantic import BaseConfig, BaseModel, Field, create_model
from pydantic.fields import FieldInfo
from typing_extensions import (
Annotated,
NotRequired,
Expand All @@ -33,13 +31,28 @@
from event_model.documents.generate.type_wrapper import (
ALLOWED_ANNOTATION_ELEMENTS,
AsRef,
BaseConfig,
BaseModel,
Field,
FieldInfo,
create_model,
extra_schema,
pydantic_version,
)

# The hacky indexing on types isn't possible with python < 3.9
if sys.version_info[:2] < (3, 9):
raise EnvironmentError("schema generation requires python 3.8 or higher")

if not pydantic_version:
raise EnvironmentError(
"schema generation requires pydantic < 2.0 to run, pydantic isn't installed"
)
elif int(pydantic_version.split(".")[0]) >= 2:
raise EnvironmentError(
"schema generation requires pydantic < 2.0 to run, current version "
f"{pydantic_version}"
)

SCHEMA_OUT_DIR = Path("event_model") / SCHEMA_PATH

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ dev = [
"numpydoc",

# For schema generation.
"pydantic",
"pydantic<2.0",
]

[project.scripts]
Expand Down

0 comments on commit a65379b

Please sign in to comment.