2525# --------------------------------------------------------------------------
2626
2727# pylint: skip-file
28+ # pyright: reportUnnecessaryTypeIgnoreComment=false
2829
2930from base64 import b64decode , b64encode
3031import calendar
3738import re
3839import sys
3940import codecs
41+ from typing import Optional , Union , AnyStr , IO , Mapping
4042
4143try :
4244 from urllib import quote # type: ignore
4345except ImportError :
44- from urllib .parse import quote # type: ignore
46+ from urllib .parse import quote
4547import xml .etree .ElementTree as ET
4648
47- import isodate
49+ import isodate # type: ignore
4850
49- from typing import Dict , Any , cast , TYPE_CHECKING
51+ from typing import Dict , Any , cast
5052
5153from azure .core .exceptions import DeserializationError , SerializationError , raise_with_traceback
5254
5355_BOM = codecs .BOM_UTF8 .decode (encoding = "utf-8" )
5456
55- if TYPE_CHECKING :
56- from typing import Optional , Union , AnyStr , IO , Mapping
57-
5857
5958class RawDeserializer :
6059
@@ -65,8 +64,7 @@ class RawDeserializer:
6564 CONTEXT_NAME = "deserialized_data"
6665
6766 @classmethod
68- def deserialize_from_text (cls , data , content_type = None ):
69- # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any
67+ def deserialize_from_text (cls , data : Optional [Union [AnyStr , IO ]], content_type : Optional [str ] = None ) -> Any :
7068 """Decode data according to content-type.
7169
7270 Accept a stream of data as well, but will be load at once in memory for now.
@@ -132,8 +130,7 @@ def _json_attemp(data):
132130 raise DeserializationError ("Cannot deserialize content-type: {}" .format (content_type ))
133131
134132 @classmethod
135- def deserialize_from_http_generics (cls , body_bytes , headers ):
136- # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any
133+ def deserialize_from_http_generics (cls , body_bytes : Optional [Union [AnyStr , IO ]], headers : Mapping ) -> Any :
137134 """Deserialize from HTTP response.
138135
139136 Use bytes and headers to NOT use any requests/aiohttp or whatever
@@ -160,8 +157,8 @@ def deserialize_from_http_generics(cls, body_bytes, headers):
160157 basestring # type: ignore
161158 unicode_str = unicode # type: ignore
162159except NameError :
163- basestring = str # type: ignore
164- unicode_str = str # type: ignore
160+ basestring = str
161+ unicode_str = str
165162
166163_LOGGER = logging .getLogger (__name__ )
167164
@@ -188,7 +185,7 @@ def dst(self, dt):
188185
189186
190187try :
191- from datetime import timezone as _FixedOffset
188+ from datetime import timezone as _FixedOffset # type: ignore
192189except ImportError : # Python 2.7
193190
194191 class _FixedOffset (datetime .tzinfo ): # type: ignore
@@ -219,7 +216,7 @@ def __getinitargs__(self):
219216try :
220217 from datetime import timezone
221218
222- TZ_UTC = timezone .utc # type: ignore
219+ TZ_UTC = timezone .utc
223220except ImportError :
224221 TZ_UTC = UTC () # type: ignore
225222
@@ -276,9 +273,9 @@ class Model(object):
276273 serialization and deserialization.
277274 """
278275
279- _subtype_map = {} # type : Dict[str, Dict[str, Any]]
280- _attribute_map = {} # type : Dict[str, Dict[str, Any]]
281- _validation = {} # type : Dict[str, Dict[str, Any]]
276+ _subtype_map : Dict [str , Dict [str , Any ]] = {}
277+ _attribute_map : Dict [str , Dict [str , Any ]] = {}
278+ _validation : Dict [str , Dict [str , Any ]] = {}
282279
283280 def __init__ (self , ** kwargs ):
284281 self .additional_properties = {}
@@ -310,7 +307,7 @@ def enable_additional_properties_sending(cls):
310307 @classmethod
311308 def is_xml_model (cls ):
312309 try :
313- cls ._xml_map
310+ cls ._xml_map # type: ignore
314311 except AttributeError :
315312 return False
316313 return True
@@ -319,7 +316,7 @@ def is_xml_model(cls):
319316 def _create_xml_node (cls ):
320317 """Create XML node."""
321318 try :
322- xml_map = cls ._xml_map
319+ xml_map = cls ._xml_map # type: ignore
323320 except AttributeError :
324321 xml_map = {}
325322
@@ -453,7 +450,7 @@ def _classify(cls, response, objects):
453450 return cls
454451 flatten_mapping_type = cls ._flatten_subtype (subtype_key , objects )
455452 try :
456- return objects [flatten_mapping_type [subtype_value ]]
453+ return objects [flatten_mapping_type [subtype_value ]] # type: ignore
457454 except KeyError :
458455 _LOGGER .warning (
459456 "Subtype value %s has no mapping, use base class %s." ,
@@ -606,13 +603,13 @@ def _serialize(self, target_obj, data_type=None, **kwargs):
606603 if xml_ns :
607604 ET .register_namespace (xml_prefix , xml_ns )
608605 xml_name = "{}{}" .format (xml_ns , xml_name )
609- serialized .set (xml_name , new_attr )
606+ serialized .set (xml_name , new_attr ) # type: ignore
610607 continue
611608 if xml_desc .get ("text" , False ):
612- serialized .text = new_attr
609+ serialized .text = new_attr # type: ignore
613610 continue
614611 if isinstance (new_attr , list ):
615- serialized .extend (new_attr )
612+ serialized .extend (new_attr ) # type: ignore
616613 elif isinstance (new_attr , ET .Element ):
617614 # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces.
618615 if "name" not in getattr (orig_attr , "_xml_map" , {}):
@@ -621,23 +618,23 @@ def _serialize(self, target_obj, data_type=None, **kwargs):
621618 new_attr .tag = "}" .join ([splitted_tag [0 ], xml_name ])
622619 else :
623620 new_attr .tag = xml_name
624- serialized .append (new_attr )
621+ serialized .append (new_attr ) # type: ignore
625622 else : # That's a basic type
626623 # Integrate namespace if necessary
627624 local_node = _create_xml_node (xml_name , xml_prefix , xml_ns )
628625 local_node .text = unicode_str (new_attr )
629- serialized .append (local_node )
626+ serialized .append (local_node ) # type: ignore
630627 else : # JSON
631- for k in reversed (keys ):
628+ for k in reversed (keys ): # type: ignore
632629 unflattened = {k : new_attr }
633630 new_attr = unflattened
634631
635632 _new_attr = new_attr
636633 _serialized = serialized
637- for k in keys :
634+ for k in keys : # type: ignore
638635 if k not in _serialized :
639- _serialized .update (_new_attr )
640- _new_attr = _new_attr [k ]
636+ _serialized .update (_new_attr ) # type: ignore
637+ _new_attr = _new_attr [k ] # type: ignore
641638 _serialized = _serialized [k ]
642639 except ValueError :
643640 continue
@@ -675,7 +672,7 @@ def body(self, data, data_type, **kwargs):
675672 # We're not able to deal with additional properties for now.
676673 deserializer .additional_properties_detection = False
677674 if is_xml_model_serialization :
678- deserializer .key_extractors = [
675+ deserializer .key_extractors = [ # type: ignore
679676 attribute_key_case_insensitive_extractor ,
680677 ]
681678 else :
@@ -843,7 +840,7 @@ def serialize_unicode(cls, data):
843840 pass
844841
845842 try :
846- if isinstance (data , unicode ):
843+ if isinstance (data , unicode ): # type: ignore
847844 # Don't change it, JSON and XML ElementTree are totally able
848845 # to serialize correctly u'' strings
849846 return data
@@ -1001,10 +998,10 @@ def serialize_enum(attr, enum_obj=None):
1001998 except AttributeError :
1002999 result = attr
10031000 try :
1004- enum_obj (result )
1001+ enum_obj (result ) # type: ignore
10051002 return result
10061003 except ValueError :
1007- for enum_value in enum_obj :
1004+ for enum_value in enum_obj : # type: ignore
10081005 if enum_value .value .lower () == str (attr ).lower ():
10091006 return enum_value .value
10101007 error = "{!r} is not valid value for enum {!r}"
@@ -1416,7 +1413,7 @@ def _deserialize(self, target_obj, data):
14161413 if data is None :
14171414 return data
14181415 try :
1419- attributes = response ._attribute_map
1416+ attributes = response ._attribute_map # type: ignore
14201417 d_attrs = {}
14211418 for attr , attr_desc in attributes .items ():
14221419 # Check empty string. If it's not empty, someone has a real "additionalProperties"...
@@ -1444,7 +1441,7 @@ def _deserialize(self, target_obj, data):
14441441 value = self .deserialize_data (raw_value , attr_desc ["type" ])
14451442 d_attrs [attr ] = value
14461443 except (AttributeError , TypeError , KeyError ) as err :
1447- msg = "Unable to deserialize to object: " + class_name
1444+ msg = "Unable to deserialize to object: " + class_name # type: ignore
14481445 raise_with_traceback (DeserializationError , msg , err )
14491446 else :
14501447 additional_properties = self ._build_additional_properties (attributes , data )
@@ -1543,7 +1540,7 @@ def _unpack_content(raw_data, content_type=None):
15431540 return RawDeserializer .deserialize_from_http_generics (raw_data .text , raw_data .headers )
15441541
15451542 if isinstance (raw_data , (basestring , bytes )) or hasattr (raw_data , "read" ):
1546- return RawDeserializer .deserialize_from_text (raw_data , content_type )
1543+ return RawDeserializer .deserialize_from_text (raw_data , content_type ) # type: ignore
15471544 return raw_data
15481545
15491546 def _instantiate_model (self , response , attrs , additional_properties = None ):
@@ -1565,7 +1562,7 @@ def _instantiate_model(self, response, attrs, additional_properties=None):
15651562 response_obj .additional_properties = additional_properties
15661563 return response_obj
15671564 except TypeError as err :
1568- msg = "Unable to deserialize {} into model {}. " .format (kwargs , response )
1565+ msg = "Unable to deserialize {} into model {}. " .format (kwargs , response ) # type: ignore
15691566 raise DeserializationError (msg + str (err ))
15701567 else :
15711568 try :
@@ -1747,7 +1744,7 @@ def deserialize_unicode(data):
17471744
17481745 # Consider this is real string
17491746 try :
1750- if isinstance (data , unicode ):
1747+ if isinstance (data , unicode ): # type: ignore
17511748 return data
17521749 except NameError :
17531750 return str (data )
@@ -1798,7 +1795,7 @@ def deserialize_bytearray(attr):
17981795 """
17991796 if isinstance (attr , ET .Element ):
18001797 attr = attr .text
1801- return bytearray (b64decode (attr ))
1798+ return bytearray (b64decode (attr )) # type: ignore
18021799
18031800 @staticmethod
18041801 def deserialize_base64 (attr ):
@@ -1810,8 +1807,8 @@ def deserialize_base64(attr):
18101807 """
18111808 if isinstance (attr , ET .Element ):
18121809 attr = attr .text
1813- padding = "=" * (3 - (len (attr ) + 3 ) % 4 )
1814- attr = attr + padding
1810+ padding = "=" * (3 - (len (attr ) + 3 ) % 4 ) # type: ignore
1811+ attr = attr + padding # type: ignore
18151812 encoded = attr .replace ("-" , "+" ).replace ("_" , "/" )
18161813 return b64decode (encoded )
18171814
@@ -1826,7 +1823,7 @@ def deserialize_decimal(attr):
18261823 if isinstance (attr , ET .Element ):
18271824 attr = attr .text
18281825 try :
1829- return decimal .Decimal (attr )
1826+ return decimal .Decimal (attr ) # type: ignore
18301827 except decimal .DecimalException as err :
18311828 msg = "Invalid decimal {}" .format (attr )
18321829 raise_with_traceback (DeserializationError , msg , err )
@@ -1841,7 +1838,7 @@ def deserialize_long(attr):
18411838 """
18421839 if isinstance (attr , ET .Element ):
18431840 attr = attr .text
1844- return _long_type (attr )
1841+ return _long_type (attr ) # type: ignore
18451842
18461843 @staticmethod
18471844 def deserialize_duration (attr ):
@@ -1871,7 +1868,7 @@ def deserialize_date(attr):
18711868 """
18721869 if isinstance (attr , ET .Element ):
18731870 attr = attr .text
1874- if re .search (r"[^\W\d_]" , attr , re .I + re .U ):
1871+ if re .search (r"[^\W\d_]" , attr , re .I + re .U ): # type: ignore
18751872 raise DeserializationError ("Date must have only digits and -. Received: %s" % attr )
18761873 # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception.
18771874 return isodate .parse_date (attr , defaultmonth = None , defaultday = None )
@@ -1886,7 +1883,7 @@ def deserialize_time(attr):
18861883 """
18871884 if isinstance (attr , ET .Element ):
18881885 attr = attr .text
1889- if re .search (r"[^\W\d_]" , attr , re .I + re .U ):
1886+ if re .search (r"[^\W\d_]" , attr , re .I + re .U ): # type: ignore
18901887 raise DeserializationError ("Date must have only digits and -. Received: %s" % attr )
18911888 return isodate .parse_time (attr )
18921889
@@ -1901,7 +1898,7 @@ def deserialize_rfc(attr):
19011898 if isinstance (attr , ET .Element ):
19021899 attr = attr .text
19031900 try :
1904- parsed_date = email .utils .parsedate_tz (attr )
1901+ parsed_date = email .utils .parsedate_tz (attr ) # type: ignore
19051902 date_obj = datetime .datetime (
19061903 * parsed_date [:6 ], tzinfo = _FixedOffset (datetime .timedelta (minutes = (parsed_date [9 ] or 0 ) / 60 ))
19071904 )
@@ -1924,7 +1921,7 @@ def deserialize_iso(attr):
19241921 if isinstance (attr , ET .Element ):
19251922 attr = attr .text
19261923 try :
1927- attr = attr .upper ()
1924+ attr = attr .upper () # type: ignore
19281925 match = Deserializer .valid_date .match (attr )
19291926 if not match :
19301927 raise ValueError ("Invalid datetime string: " + attr )
@@ -1960,7 +1957,7 @@ def deserialize_unix(attr):
19601957 :raises: DeserializationError if format invalid
19611958 """
19621959 if isinstance (attr , ET .Element ):
1963- attr = int (attr .text )
1960+ attr = int (attr .text ) # type: ignore
19641961 try :
19651962 date_obj = datetime .datetime .fromtimestamp (attr , TZ_UTC )
19661963 except ValueError as err :
0 commit comments