Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from collections.abc import MutableMapping
from io import IOBase
import json
from typing import Any, Callable, Dict, IO, Iterator, List, Optional, TypeVar, Union, cast, overload
from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload
import urllib.parse

from azure.core import PipelineClient
Expand Down Expand Up @@ -38,7 +38,7 @@

JSON = MutableMapping[str, Any]
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]]

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
Expand Down Expand Up @@ -193,8 +193,6 @@ def build_deidentification_delete_job_request( # pylint: disable=name-too-long
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})

api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-07-15-preview"))
accept = _headers.pop("Accept", "application/json")

# Construct URL
_url = "/jobs/{name}"
path_format_arguments = {
Expand All @@ -207,7 +205,6 @@ def build_deidentification_delete_job_request( # pylint: disable=name-too-long
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

# Construct headers
_headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)

Expand Down Expand Up @@ -538,7 +535,7 @@ def _list_jobs_internal(
_params = kwargs.pop("params", {}) or {}

maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.DeidentificationJob]] = kwargs.pop("cls", None)
cls: ClsType[list[_models.DeidentificationJob]] = kwargs.pop("cls", None)

error_map: MutableMapping = {
401: ClientAuthenticationError,
Expand Down Expand Up @@ -589,7 +586,7 @@ def prepare_request(next_link=None):

def extract_data(pipeline_response):
deserialized = pipeline_response.http_response.json()
list_of_elem = _deserialize(List[_models.DeidentificationJob], deserialized.get("value", []))
list_of_elem = _deserialize(list[_models.DeidentificationJob], deserialized.get("value", []))
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.get("nextLink") or None, iter(list_of_elem)
Expand Down Expand Up @@ -633,7 +630,7 @@ def _list_job_documents_internal(
_params = kwargs.pop("params", {}) or {}

maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.DeidentificationDocumentDetails]] = kwargs.pop("cls", None)
cls: ClsType[list[_models.DeidentificationDocumentDetails]] = kwargs.pop("cls", None)

error_map: MutableMapping = {
401: ClientAuthenticationError,
Expand Down Expand Up @@ -685,7 +682,7 @@ def prepare_request(next_link=None):

def extract_data(pipeline_response):
deserialized = pipeline_response.http_response.json()
list_of_elem = _deserialize(List[_models.DeidentificationDocumentDetails], deserialized.get("value", []))
list_of_elem = _deserialize(list[_models.DeidentificationDocumentDetails], deserialized.get("value", []))
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return deserialized.get("nextLink") or None, iter(list_of_elem)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from azure.core import CaseInsensitiveEnumMeta
from azure.core.pipeline import PipelineResponse
from azure.core.serialization import _Null
from azure.core.rest import HttpResponse

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -345,7 +346,7 @@ def _get_model(module_name: str, model_name: str):


class _MyMutableMapping(MutableMapping[str, typing.Any]):
def __init__(self, data: typing.Dict[str, typing.Any]) -> None:
def __init__(self, data: dict[str, typing.Any]) -> None:
self._data = data

def __contains__(self, key: typing.Any) -> bool:
Expand Down Expand Up @@ -425,7 +426,7 @@ def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any:
return self._data.pop(key)
return self._data.pop(key, default)

def popitem(self) -> typing.Tuple[str, typing.Any]:
def popitem(self) -> tuple[str, typing.Any]:
"""
Removes and returns some (key, value) pair
:returns: The (key, value) pair.
Expand Down Expand Up @@ -513,9 +514,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m
return o


def _get_rest_field(
attr_to_rest_field: typing.Dict[str, "_RestField"], rest_name: str
) -> typing.Optional["_RestField"]:
def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]:
try:
return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name)
except StopIteration:
Expand All @@ -538,7 +537,7 @@ class Model(_MyMutableMapping):
_is_model = True
# label whether current class's _attr_to_rest_field has been calculated
# could not see _attr_to_rest_field directly because subclass inherits it from parent class
_calculated: typing.Set[str] = set()
_calculated: set[str] = set()

def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
class_name = self.__class__.__name__
Expand Down Expand Up @@ -623,7 +622,7 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self:
# we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping',
# 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object'
mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order
attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property
attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property
k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type")
}
annotations = {
Expand All @@ -638,7 +637,7 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self:
rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None))
if not rf._rest_name_input:
rf._rest_name_input = attr
cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items())
cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items())
cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}")

return super().__new__(cls)
Expand Down Expand Up @@ -680,7 +679,7 @@ def _deserialize(cls, data, exist_discriminators):
mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member
return mapped_cls._deserialize(data, exist_discriminators)

def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.Any]:
def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]:
"""Return a dict that can be turned into json using json.dump.

:keyword bool exclude_readonly: Whether to remove the readonly properties.
Expand Down Expand Up @@ -740,7 +739,7 @@ def _deserialize_with_union(deserializers, obj):
def _deserialize_dict(
value_deserializer: typing.Optional[typing.Callable],
module: typing.Optional[str],
obj: typing.Dict[typing.Any, typing.Any],
obj: dict[typing.Any, typing.Any],
):
if obj is None:
return obj
Expand All @@ -750,7 +749,7 @@ def _deserialize_dict(


def _deserialize_multiple_sequence(
entry_deserializers: typing.List[typing.Optional[typing.Callable]],
entry_deserializers: list[typing.Optional[typing.Callable]],
module: typing.Optional[str],
obj,
):
Expand All @@ -771,14 +770,14 @@ def _deserialize_sequence(
return type(obj)(_deserialize(deserializer, entry, module) for entry in obj)


def _sorted_annotations(types: typing.List[typing.Any]) -> typing.List[typing.Any]:
def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]:
return sorted(
types,
key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"),
)


def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-branches
def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches
annotation: typing.Any,
module: typing.Optional[str],
rf: typing.Optional["_RestField"] = None,
Expand Down Expand Up @@ -843,7 +842,10 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur
return functools.partial(_deserialize_with_union, deserializers)

try:
if annotation._name == "Dict": # pyright: ignore
annotation_name = (
annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore
)
if annotation_name.lower() == "dict":
value_deserializer = _get_deserialize_callable_from_annotation(
annotation.__args__[1], module, rf # pyright: ignore
)
Expand All @@ -856,7 +858,10 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-retur
except (AttributeError, IndexError):
pass
try:
if annotation._name in ["List", "Set", "Tuple", "Sequence"]: # pyright: ignore
annotation_name = (
annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore
)
if annotation_name.lower() in ["list", "set", "tuple", "sequence"]:
if len(annotation.__args__) > 1: # pyright: ignore
entry_deserializers = [
_get_deserialize_callable_from_annotation(dt, module, rf)
Expand Down Expand Up @@ -940,13 +945,13 @@ def _deserialize(

def _failsafe_deserialize(
deserializer: typing.Any,
value: typing.Any,
response: HttpResponse,
module: typing.Optional[str] = None,
rf: typing.Optional["_RestField"] = None,
format: typing.Optional[str] = None,
) -> typing.Any:
try:
return _deserialize(deserializer, value, module, rf, format)
return _deserialize(deserializer, response.json(), module, rf, format)
except DeserializationError:
_LOGGER.warning(
"Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True
Expand All @@ -956,10 +961,10 @@ def _failsafe_deserialize(

def _failsafe_deserialize_xml(
deserializer: typing.Any,
value: typing.Any,
response: HttpResponse,
) -> typing.Any:
try:
return _deserialize_xml(deserializer, value)
return _deserialize_xml(deserializer, response.text())
except DeserializationError:
_LOGGER.warning(
"Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True
Expand All @@ -974,11 +979,11 @@ def __init__(
name: typing.Optional[str] = None,
type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin
is_discriminator: bool = False,
visibility: typing.Optional[typing.List[str]] = None,
visibility: typing.Optional[list[str]] = None,
default: typing.Any = _UNSET,
format: typing.Optional[str] = None,
is_multipart_file_input: bool = False,
xml: typing.Optional[typing.Dict[str, typing.Any]] = None,
xml: typing.Optional[dict[str, typing.Any]] = None,
):
self._type = type
self._rest_name_input = name
Expand Down Expand Up @@ -1036,11 +1041,11 @@ def rest_field(
*,
name: typing.Optional[str] = None,
type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin
visibility: typing.Optional[typing.List[str]] = None,
visibility: typing.Optional[list[str]] = None,
default: typing.Any = _UNSET,
format: typing.Optional[str] = None,
is_multipart_file_input: bool = False,
xml: typing.Optional[typing.Dict[str, typing.Any]] = None,
xml: typing.Optional[dict[str, typing.Any]] = None,
) -> typing.Any:
return _RestField(
name=name,
Expand All @@ -1057,8 +1062,8 @@ def rest_discriminator(
*,
name: typing.Optional[str] = None,
type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin
visibility: typing.Optional[typing.List[str]] = None,
xml: typing.Optional[typing.Dict[str, typing.Any]] = None,
visibility: typing.Optional[list[str]] = None,
xml: typing.Optional[dict[str, typing.Any]] = None,
) -> typing.Any:
return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml)

Expand All @@ -1077,9 +1082,9 @@ def serialize_xml(model: Model, exclude_readonly: bool = False) -> str:
def _get_element(
o: typing.Any,
exclude_readonly: bool = False,
parent_meta: typing.Optional[typing.Dict[str, typing.Any]] = None,
parent_meta: typing.Optional[dict[str, typing.Any]] = None,
wrapped_element: typing.Optional[ET.Element] = None,
) -> typing.Union[ET.Element, typing.List[ET.Element]]:
) -> typing.Union[ET.Element, list[ET.Element]]:
if _is_model(o):
model_meta = getattr(o, "_xml", {})

Expand Down Expand Up @@ -1168,7 +1173,7 @@ def _get_element(
def _get_wrapped_element(
v: typing.Any,
exclude_readonly: bool,
meta: typing.Optional[typing.Dict[str, typing.Any]],
meta: typing.Optional[dict[str, typing.Any]],
) -> ET.Element:
wrapped_element = _create_xml_element(
meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None
Expand Down Expand Up @@ -1211,7 +1216,7 @@ def _deserialize_xml(
def _convert_element(e: ET.Element):
# dict case
if len(e.attrib) > 0 or len({child.tag for child in e}) > 1:
dict_result: typing.Dict[str, typing.Any] = {}
dict_result: dict[str, typing.Any] = {}
for child in e:
if dict_result.get(child.tag) is not None:
if isinstance(dict_result[child.tag], list):
Expand All @@ -1224,7 +1229,7 @@ def _convert_element(e: ET.Element):
return dict_result
# array case
if len(e) > 0:
array_result: typing.List[typing.Any] = []
array_result: list[typing.Any] = []
for child in e:
array_result.append(_convert_element(child))
return array_result
Expand Down
Loading
Loading