Skip to content

Commit

Permalink
updates for python 3.8
Browse files Browse the repository at this point in the history
  • Loading branch information
tlambert03 committed Nov 21, 2024
1 parent 203dbe8 commit 6ede683
Show file tree
Hide file tree
Showing 24 changed files with 83 additions and 67 deletions.
3 changes: 2 additions & 1 deletion docs/scripts/write_v2_changes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import json
from pathlib import Path
from typing import TYPE_CHECKING, Any, Iterator
from typing import TYPE_CHECKING, Any

from deepdiff import DeepDiff
from fuzzywuzzy import fuzz
Expand All @@ -12,6 +12,7 @@
from ome_types.model import Reference

if TYPE_CHECKING:
from collections.abc import Iterator
from types import ModuleType

DOCS = Path(__file__).parent.parent
Expand Down
9 changes: 6 additions & 3 deletions src/ome_autogen/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@
import re
from collections import defaultdict
from contextlib import contextmanager
from functools import lru_cache
from functools import cache
from pathlib import Path
from typing import Any, Iterator, NamedTuple, cast
from typing import TYPE_CHECKING, Any, NamedTuple, cast
from xml.etree import ElementTree as ET

if TYPE_CHECKING:
from collections.abc import Iterator

SRC_PATH = Path(__file__).parent.parent
SCHEMA_FILE = (SRC_PATH / "ome_types" / "ome-2016-06.xsd").absolute()

Expand Down Expand Up @@ -40,7 +43,7 @@ class AppInfo(NamedTuple):
abstract: list[str]


@lru_cache(maxsize=None)
@cache
def get_appinfo(schema: Path | str = SCHEMA_FILE) -> AppInfo:
"""Gather all the <xsd:appinfo> stuff from the schema.
Expand Down
4 changes: 3 additions & 1 deletion src/ome_autogen/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Iterator, cast
from typing import TYPE_CHECKING, cast

from xsdata.formats.dataclass.filters import Filters
from xsdata.formats.dataclass.generator import DataclassGenerator
Expand All @@ -12,6 +12,8 @@
from xsdata_pydantic_basemodel.generator import PydanticBaseFilters

if TYPE_CHECKING:
from collections.abc import Iterator

from jinja2 import Environment, FileSystemLoader
from xsdata.codegen.models import Attr, Class
from xsdata.codegen.resolver import DependenciesResolver
Expand Down
5 changes: 4 additions & 1 deletion src/ome_autogen/overrides.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import Sequence
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from collections.abc import Sequence

# from ome_types._mixins._base_type import AUTO_SEQUENCE
# avoiding import to avoid build-time dependency on the ome-types package
Expand Down
4 changes: 3 additions & 1 deletion src/ome_autogen/transformer.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
from __future__ import annotations

from contextlib import contextmanager
from typing import TYPE_CHECKING, Iterator
from typing import TYPE_CHECKING

from xsdata.codegen.analyzer import ClassAnalyzer
from xsdata.codegen.container import ClassContainer
from xsdata.codegen.handlers import RenameDuplicateAttributes
from xsdata.codegen.mappers.schema import SchemaMapper

if TYPE_CHECKING:
from collections.abc import Iterator

from xsdata.codegen.transformer import ResourceTransformer

else:
Expand Down
12 changes: 7 additions & 5 deletions src/ome_types/_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
import os
import warnings
from contextlib import nullcontext, suppress
from functools import lru_cache
from functools import cache
from pathlib import Path
from struct import Struct
from typing import TYPE_CHECKING, Callable, Iterable, cast, overload
from typing import TYPE_CHECKING, Callable, cast, overload

from pydantic import BaseModel
from xsdata.formats.dataclass.parsers.config import ParserConfig
Expand All @@ -26,7 +26,9 @@


if TYPE_CHECKING:
from typing import Any, BinaryIO, ContextManager, Literal, TypedDict
from collections.abc import Iterable
from contextlib import AbstractContextManager
from typing import Any, BinaryIO, Literal, TypedDict
from xml.etree import ElementTree

import xmlschema
Expand Down Expand Up @@ -174,7 +176,7 @@ def _unpack(fh: BinaryIO, strct: Struct) -> int:
def tiff2xml(path: Path | str | BinaryIO) -> bytes:
"""Extract the OME-XML from a TIFF file."""
if hasattr(path, "read"):
ctx: ContextManager[BinaryIO] = nullcontext(path) # type: ignore[arg-type]
ctx: AbstractContextManager[BinaryIO] = nullcontext(path) # type: ignore[arg-type]
else:
ctx = Path(path).open(mode="rb")

Expand Down Expand Up @@ -389,7 +391,7 @@ def validate_xml_with_xmlschema(
return tree


@lru_cache(maxsize=None)
@cache
def _get_XMLSchema(schema: Path | str) -> xmlschema.XMLSchema:
import xmlschema

Expand Down
14 changes: 5 additions & 9 deletions src/ome_types/_mixins/_base_type.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import warnings
from collections.abc import Sequence
from datetime import datetime
from enum import Enum
from textwrap import indent
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Dict,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
cast,
)
Expand Down Expand Up @@ -53,7 +49,7 @@
}


def _move_deprecated_fields(data: Dict[str, Any], field_names: Set[str]) -> None:
def _move_deprecated_fields(data: dict[str, Any], field_names: set[str]) -> None:
for key in list(data):
if (
key not in field_names
Expand Down Expand Up @@ -90,7 +86,7 @@ class OMEType(BaseModel):

# allow use with weakref
if not PYDANTIC2:
__slots__: ClassVar[Set[str]] = {"__weakref__"} # type: ignore
__slots__: ClassVar[set[str]] = {"__weakref__"} # type: ignore

Check warning on line 89 in src/ome_types/_mixins/_base_type.py

View check run for this annotation

Codecov / codecov/patch

src/ome_types/_mixins/_base_type.py#L89

Added line #L89 was not covered by tests

_vid = field_validator("id", mode="before", check_fields=False)(validate_id)

Expand Down Expand Up @@ -121,7 +117,7 @@ def __init_subclass__(cls) -> None:
"""
add_quantity_properties(cls)

def __repr_args__(self) -> Sequence[Tuple[Optional[str], Any]]:
def __repr_args__(self) -> Sequence[tuple[Optional[str], Any]]:
"""Repr with only set values, and truncated sequences."""
args = []
for k, v in self.model_dump(exclude_defaults=True).items():
Expand Down Expand Up @@ -177,7 +173,7 @@ def to_xml(self, **kwargs: Any) -> str:
return to_xml(self, **kwargs)

@classmethod
def from_xml(cls: Type[T], xml: "XMLSource", **kwargs: Any) -> T:
def from_xml(cls: type[T], xml: "XMLSource", **kwargs: Any) -> T:
"""Read an ome-types class from XML.
See docstring of [`ome_types.from_xml`][] for kwargs.
Expand Down
5 changes: 3 additions & 2 deletions src/ome_types/_mixins/_collections.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import itertools
from typing import Any, Generic, Iterator, List, TypeVar, Union, cast, no_type_check
from collections.abc import Iterator
from typing import Any, Generic, TypeVar, Union, cast, no_type_check

from pydantic import BaseModel

Expand Down Expand Up @@ -50,7 +51,7 @@ def append(self, item: T) -> None:
"""Append an item to the appropriate field list."""
cast(list, getattr(self, self._field_name(item))).append(item)

def extend(self, items: List[T]) -> None:
def extend(self, items: list[T]) -> None:
"""Extend the appropriate field list with the given items."""
for item in items:
self.append(item)
Expand Down
4 changes: 2 additions & 2 deletions src/ome_types/_mixins/_instrument.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import TYPE_CHECKING, List, Union, cast
from typing import TYPE_CHECKING, Union, cast

if TYPE_CHECKING:
from ome_types._autogenerated.ome_2016_06 import (
Expand All @@ -17,7 +17,7 @@

class InstrumentMixin:
@property
def light_source_group(self) -> List["LightSource"]:
def light_source_group(self) -> list["LightSource"]:
# here for backwards compatibility
slf = cast("Instrument", self)
return [
Expand Down
7 changes: 4 additions & 3 deletions src/ome_types/_mixins/_kinded.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Any, Dict
import builtins
from typing import Any

from pydantic_compat import BaseModel

Expand All @@ -19,15 +20,15 @@ def __init__(self, **data: Any) -> None:
data.pop("kind", None)
return super().__init__(**data)

def dict(self, **kwargs: Any) -> Dict[str, Any]:
def dict(self, **kwargs: Any) -> dict[str, Any]:
d = super().dict(**kwargs)
d["kind"] = self.__class__.__name__.lower()
return d

if model_serializer is not None:

@model_serializer(mode="wrap")
def serialize_root(self, handler, _info) -> Dict: # type: ignore
def serialize_root(self, handler, _info) -> builtins.dict: # type: ignore
d = handler(self)
d["kind"] = self.__class__.__name__.lower()
return d
9 changes: 5 additions & 4 deletions src/ome_types/_mixins/_map_mixin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, MutableMapping, Optional
from collections.abc import Iterator, MutableMapping
from typing import TYPE_CHECKING, Any, Optional

try:
from pydantic import model_serializer
Expand All @@ -13,7 +14,7 @@

class HasMsProtocol(Protocol):
@property
def ms(self) -> List["Map.M"]: ...
def ms(self) -> list["Map.M"]: ...


class MapMixin(MutableMapping[str, Optional[str]]):
Expand Down Expand Up @@ -41,10 +42,10 @@ def __setitem__(self: "HasMsProtocol", key: str, value: Optional[str]) -> None:

self.ms.append(Map.M(k=key, value=value))

def _pydict(self: "HasMsProtocol", **kwargs: Any) -> Dict[str, str]:
def _pydict(self: "HasMsProtocol", **kwargs: Any) -> dict[str, str]:
return {m.k: m.value for m in self.ms if m.k is not None}

def dict(self, **kwargs: Any) -> Dict[str, Any]:
def dict(self, **kwargs: Any) -> dict[str, Any]:
return self._pydict() # type: ignore

if model_serializer is not None:
Expand Down
3 changes: 2 additions & 1 deletion src/ome_types/_mixins/_ome.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import warnings
import weakref
from typing import TYPE_CHECKING, Any, BinaryIO, Sequence
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any, BinaryIO

from ome_types._mixins._base_type import OMEType
from ome_types._mixins._ids import CONVERTED_IDS
Expand Down
4 changes: 2 additions & 2 deletions src/ome_types/_mixins/_reference.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import weakref
from typing import Any, Dict, Optional, Union
from typing import Any, Optional, Union

from pydantic import PrivateAttr

Expand All @@ -15,7 +15,7 @@ def ref(self) -> Union[OMEType, None]:
raise ValueError("references not yet resolved on root OME object")
return self._ref()

def __getstate__(self: Any) -> Dict[str, Any]:
def __getstate__(self: Any) -> dict[str, Any]:
"""Support pickle of our weakref references."""
state = super().__getstate__()
if "__private_attribute_values__" in state:
Expand Down
9 changes: 5 additions & 4 deletions src/ome_types/_mixins/_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"""

import warnings
from typing import TYPE_CHECKING, Any, Dict, List, Sequence
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
from ome_types.model import ( # type: ignore
Expand All @@ -21,7 +22,7 @@


# @model_validator(mode='before')
def bin_data_root_validator(cls: "BinData", values: dict) -> Dict[str, Any]:
def bin_data_root_validator(cls: "BinData", values: dict) -> dict[str, Any]:
# This catches the case of <BinData Length="0"/>, where the parser may have
# omitted value from the dict, and sets value to b""
# seems like it could be done in a default_factory, but that would
Expand Down Expand Up @@ -52,8 +53,8 @@ def pixels_root_validator(cls: "Pixels", value: dict) -> dict:

# @validator("any_elements")
def any_elements_validator(
cls: "XMLAnnotation.Value", v: List[Any]
) -> List["AnyElement"]:
cls: "XMLAnnotation.Value", v: list[Any]
) -> list["AnyElement"]:
# This validator is used because XMLAnnotation.Value.any_elements is
# annotated as List[object]. So pydantic won't coerce dicts to AnyElement
# automatically (which is important when constructing OME objects from dicts)
Expand Down
3 changes: 2 additions & 1 deletion src/ome_types/_pydantic_compat.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Any, MutableSequence, cast
from collections.abc import MutableSequence
from typing import TYPE_CHECKING, Any, cast

import pydantic.version
from pydantic import BaseModel
Expand Down
3 changes: 2 additions & 1 deletion src/ome_types/model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import sys
from importlib.abc import Loader, MetaPathFinder
from pathlib import Path
from typing import TYPE_CHECKING, Any, Sequence
from typing import TYPE_CHECKING, Any

from ome_types._autogenerated.ome_2016_06 import * # noqa

Expand All @@ -15,6 +15,7 @@
from ome_types.model._color import Color as Color

if TYPE_CHECKING:
from collections.abc import Sequence
from importlib.machinery import ModuleSpec
from types import ModuleType

Expand Down
6 changes: 3 additions & 3 deletions src/ome_types/model/_color.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from contextlib import suppress
from typing import Tuple, Union
from typing import Union

from ome_types._vendor import Color as _Color

__all__ = ["Color"]

RGBA = Tuple[int, int, int, float]
ColorType = Union[Tuple[int, int, int], RGBA, str, int]
RGBA = tuple[int, int, int, float]
ColorType = Union[tuple[int, int, int], RGBA, str, int]


class Color(_Color):
Expand Down
4 changes: 3 additions & 1 deletion src/xsdata_pydantic_basemodel/bindings.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Callable, Generator, Iterator
from typing import TYPE_CHECKING, Any, Callable
from xml.etree.ElementTree import QName

from xsdata.formats.dataclass import context, parsers, serializers
Expand All @@ -12,6 +12,8 @@
from xsdata.utils.constants import EMPTY_MAP, return_input

if TYPE_CHECKING:
from collections.abc import Generator, Iterator

from pydantic import BaseModel
from xsdata.formats.dataclass.models.elements import XmlMeta

Expand Down
Loading

0 comments on commit 6ede683

Please sign in to comment.