From: Bob Halley Date: Tue, 23 Dec 2025 17:30:06 +0000 (-0800) Subject: Convert deprecated typing module types to modern forms. X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=24a6731bfaf8b8a2ac34962d0df59068f6c1f5b0;p=thirdparty%2Fdnspython.git Convert deprecated typing module types to modern forms. --- diff --git a/dns/_features.py b/dns/_features.py index 65a9a2a3..c2b32862 100644 --- a/dns/_features.py +++ b/dns/_features.py @@ -3,10 +3,9 @@ import importlib.metadata import itertools import string -from typing import Dict, List, Tuple -def _tuple_from_text(version: str) -> Tuple: +def _tuple_from_text(version: str) -> tuple: text_parts = version.split(".") int_parts = [] for text_part in text_parts: @@ -44,7 +43,7 @@ def _version_check( return True -_cache: Dict[str, bool] = {} +_cache: dict[str, bool] = {} def have(feature: str) -> bool: @@ -83,7 +82,7 @@ def force(feature: str, enabled: bool) -> None: _cache[feature] = enabled -_requirements: Dict[str, List[str]] = { +_requirements: dict[str, list[str]] = { ### BEGIN generated requirements "dnssec": ["cryptography>=45"], "doh": ["httpcore>=1.0.0", "httpx>=0.28.0", "h2>=4.2.0"], diff --git a/dns/_tls_util.py b/dns/_tls_util.py index 10ddf727..9e46e79f 100644 --- a/dns/_tls_util.py +++ b/dns/_tls_util.py @@ -1,12 +1,11 @@ # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license import os -from typing import Tuple def convert_verify_to_cafile_and_capath( verify: bool | str, -) -> Tuple[str | None, str | None]: +) -> tuple[str | None, str | None]: cafile: str | None = None capath: str | None = None if isinstance(verify, str): diff --git a/dns/asyncbackend.py b/dns/asyncbackend.py index 0ec58b06..831ec6e9 100644 --- a/dns/asyncbackend.py +++ b/dns/asyncbackend.py @@ -1,7 +1,5 @@ # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license -from typing import Dict - import dns.exception # pylint: disable=unused-import @@ -16,7 +14,7 @@ from dns._asyncbackend import ( # noqa: F401 lgtm[py/unused-import] _default_backend = None -_backends: Dict[str, Backend] = {} +_backends: dict[str, Backend] = {} # Allow sniffio import to be disabled for testing purposes _no_sniffio = False diff --git a/dns/asyncquery.py b/dns/asyncquery.py index 36905a20..7ec7ed82 100644 --- a/dns/asyncquery.py +++ b/dns/asyncquery.py @@ -24,7 +24,7 @@ import socket import struct import time import urllib.parse -from typing import Any, Dict, Optional, Tuple, cast +from typing import Any, cast import dns.asyncbackend import dns.exception @@ -93,7 +93,7 @@ async def send_udp( what: dns.message.Message | bytes, destination: Any, expiration: float | None = None, -) -> Tuple[int, float]: +) -> tuple[int, float]: """Send a DNS message to the specified UDP socket. *sock*, a ``dns.asyncbackend.DatagramSocket``. @@ -124,7 +124,7 @@ async def receive_udp( expiration: float | None = None, ignore_unexpected: bool = False, one_rr_per_rrset: bool = False, - keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, + keyring: dict[dns.name.Name, dns.tsig.Key] | None = None, request_mac: bytes | None = b"", ignore_trailing: bool = False, raise_on_truncation: bool = False, @@ -259,7 +259,7 @@ async def udp_with_fallback( tcp_sock: dns.asyncbackend.StreamSocket | None = None, backend: dns.asyncbackend.Backend | None = None, ignore_errors: bool = False, -) -> Tuple[dns.message.Message, bool]: +) -> tuple[dns.message.Message, bool]: """Return the response to the query, trying UDP first and falling back to TCP if UDP results in a truncated response. @@ -317,7 +317,7 @@ async def send_tcp( sock: dns.asyncbackend.StreamSocket, what: dns.message.Message | bytes, expiration: float | None = None, -) -> Tuple[int, float]: +) -> tuple[int, float]: """Send a DNS message to the specified TCP socket. *sock*, a ``dns.asyncbackend.StreamSocket``. @@ -356,10 +356,10 @@ async def receive_tcp( sock: dns.asyncbackend.StreamSocket, expiration: float | None = None, one_rr_per_rrset: bool = False, - keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, + keyring: dict[dns.name.Name, dns.tsig.Key] | None = None, request_mac: bytes | None = b"", ignore_trailing: bool = False, -) -> Tuple[dns.message.Message, float]: +) -> tuple[dns.message.Message, float]: """Read a DNS message from a TCP socket. *sock*, a ``dns.asyncbackend.StreamSocket``. @@ -514,7 +514,7 @@ async def tls( def _maybe_get_resolver( - resolver: Optional["dns.asyncresolver.Resolver"], # type: ignore + resolver: "dns.asyncresolver.Resolver | None", # type: ignore ) -> "dns.asyncresolver.Resolver": # type: ignore # We need a separate method for this to avoid overriding the global # variable "dns" with the as-yet undefined local variable "dns" @@ -536,12 +536,12 @@ async def https( source_port: int = 0, # pylint: disable=W0613 one_rr_per_rrset: bool = False, ignore_trailing: bool = False, - client: Optional["httpx.AsyncClient|dns.quic.AsyncQuicConnection"] = None, + client: "httpx.AsyncClient|dns.quic.AsyncQuicConnection | None" = None, path: str = "/dns-query", post: bool = True, verify: bool | str | ssl.SSLContext = True, bootstrap_address: str | None = None, - resolver: Optional["dns.asyncresolver.Resolver"] = None, # type: ignore + resolver: "dns.asyncresolver.Resolver | None" = None, # type: ignore family: int = socket.AF_UNSPEC, http_version: HTTPVersion = HTTPVersion.DEFAULT, ) -> dns.message.Message: diff --git a/dns/asyncresolver.py b/dns/asyncresolver.py index 6f8c69fd..52edc63e 100644 --- a/dns/asyncresolver.py +++ b/dns/asyncresolver.py @@ -19,12 +19,11 @@ import socket import time -from typing import Any, Dict, List +from typing import Any import dns._ddr import dns.asyncbackend import dns.asyncquery -import dns.exception import dns.inet import dns.name import dns.nameserver @@ -130,7 +129,7 @@ class Resolver(dns.resolver.BaseResolver): # We make a modified kwargs for type checking happiness, as otherwise # we get a legit warning about possibly having rdtype and rdclass # in the kwargs more than once. - modified_kwargs: Dict[str, Any] = {} + modified_kwargs: dict[str, Any] = {} modified_kwargs.update(kwargs) modified_kwargs["rdtype"] = dns.rdatatype.PTR modified_kwargs["rdclass"] = dns.rdataclass.IN @@ -161,7 +160,7 @@ class Resolver(dns.resolver.BaseResolver): # We make a modified kwargs for type checking happiness, as otherwise # we get a legit warning about possibly having rdtype and rdclass # in the kwargs more than once. - modified_kwargs: Dict[str, Any] = {} + modified_kwargs: dict[str, Any] = {} modified_kwargs.update(kwargs) modified_kwargs.pop("rdtype", None) modified_kwargs["rdclass"] = dns.rdataclass.IN @@ -422,7 +421,7 @@ async def make_resolver_at( """ if resolver is None: resolver = get_default_resolver() - nameservers: List[str | dns.nameserver.Nameserver] = [] + nameservers: list[str | dns.nameserver.Nameserver] = [] if isinstance(where, str) and dns.inet.is_address(where): nameservers.append(dns.nameserver.Do53Nameserver(where, port)) else: diff --git a/dns/btree.py b/dns/btree.py index e4d42973..5c1156b0 100644 --- a/dns/btree.py +++ b/dns/btree.py @@ -6,8 +6,8 @@ copy-on-write node updates, cursors, and optional space optimization for mostly- insertion. """ -from collections.abc import MutableMapping, MutableSet -from typing import Callable, Generic, Optional, Tuple, TypeVar, cast +from collections.abc import Callable, MutableMapping, MutableSet +from typing import Generic, TypeVar, cast DEFAULT_T = 127 @@ -114,7 +114,7 @@ class _Node(Generic[KT, ET]): else: return child - def _get_node(self, key: KT) -> Tuple[Optional["_Node[KT, ET]"], int]: + def _get_node(self, key: KT) -> tuple["_Node[KT, ET] | None", int]: """Get the node associated with key and its index, doing copy-on-write if we have to descend. @@ -292,7 +292,7 @@ class _Node(Generic[KT, ET]): left.merge(parent, index - 1) def delete( - self, key: KT, parent: Optional["_Node[KT, ET]"], exact: ET | None + self, key: KT, parent: "_Node[KT, ET] | None", exact: ET | None ) -> ET | None: """Delete an element matching *key* if it exists. If *exact* is not ``None`` then it must be an exact match with that element. The Node must not be @@ -354,7 +354,7 @@ class _Node(Generic[KT, ET]): for child in self.children: child._visit_preorder_by_node(visit) - def maybe_cow(self, creator: _Creator) -> Optional["_Node[KT, ET]"]: + def maybe_cow(self, creator: _Creator) -> "_Node[KT, ET] | None": """Return a clone of this Node if it was not created by *creator*, or ``None`` otherwise (i.e. copy for copy-on-write if we haven't already copied it).""" if self.creator is not creator: @@ -613,7 +613,7 @@ class Immutable(Exception): class BTree(Generic[KT, ET]): """An in-memory BTree with copy-on-write and cursors.""" - def __init__(self, *, t: int = DEFAULT_T, original: Optional["BTree"] = None): + def __init__(self, *, t: int = DEFAULT_T, original: "BTree | None" = None): """Create a BTree. If *original* is not ``None``, then the BTree is shallow-cloned from diff --git a/dns/btreezone.py b/dns/btreezone.py index 27b5bb6f..b1b477d7 100644 --- a/dns/btreezone.py +++ b/dns/btreezone.py @@ -12,8 +12,9 @@ # points, and the GLUE flag is set on nodes beneath delegation points. import enum +from collections.abc import Callable, MutableMapping from dataclasses import dataclass -from typing import Callable, MutableMapping, Tuple, cast +from typing import cast import dns.btree import dns.immutable @@ -106,7 +107,7 @@ class ImmutableNode(Node): class Delegations(dns.btree.BTreeSet[dns.name.Name]): - def get_delegation(self, name: dns.name.Name) -> Tuple[dns.name.Name | None, bool]: + def get_delegation(self, name: dns.name.Name) -> tuple[dns.name.Name | None, bool]: """Get the delegation applicable to *name*, if it exists. If there delegation, then return a tuple consisting of the name of @@ -160,7 +161,7 @@ class WritableVersion(dns.zone.WritableVersion): def _maybe_cow_with_name( self, name: dns.name.Name - ) -> Tuple[dns.node.Node, dns.name.Name]: + ) -> tuple[dns.node.Node, dns.name.Name]: (node, name) = super()._maybe_cow_with_name(name) node = cast(Node, node) if self._is_origin(name): diff --git a/dns/dnssec.py b/dns/dnssec.py index 0b2aa709..020a3ffd 100644 --- a/dns/dnssec.py +++ b/dns/dnssec.py @@ -25,8 +25,9 @@ import functools import hashlib import struct import time +from collections.abc import Callable from datetime import datetime -from typing import Callable, Dict, List, Set, Tuple, Union, cast +from typing import Union, cast import dns._features import dns.name @@ -292,8 +293,8 @@ def make_cds( def _find_candidate_keys( - keys: Dict[dns.name.Name, dns.rdataset.Rdataset | dns.node.Node], rrsig: RRSIG -) -> List[DNSKEY] | None: + keys: dict[dns.name.Name, dns.rdataset.Rdataset | dns.node.Node], rrsig: RRSIG +) -> list[DNSKEY] | None: value = keys.get(rrsig.signer) if isinstance(value, dns.node.Node): rdataset = value.get_rdataset(dns.rdataclass.IN, dns.rdatatype.DNSKEY) @@ -312,8 +313,8 @@ def _find_candidate_keys( def _get_rrname_rdataset( - rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], -) -> Tuple[dns.name.Name, dns.rdataset.Rdataset]: + rrset: dns.rrset.RRset | tuple[dns.name.Name, dns.rdataset.Rdataset], +) -> tuple[dns.name.Name, dns.rdataset.Rdataset]: if isinstance(rrset, tuple): return rrset[0], rrset[1] else: @@ -331,9 +332,9 @@ def _validate_signature(sig: bytes, data: bytes, key: DNSKEY) -> None: def _validate_rrsig( - rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], + rrset: dns.rrset.RRset | tuple[dns.name.Name, dns.rdataset.Rdataset], rrsig: RRSIG, - keys: Dict[dns.name.Name, dns.node.Node | dns.rdataset.Rdataset], + keys: dict[dns.name.Name, dns.node.Node | dns.rdataset.Rdataset], origin: dns.name.Name | None = None, now: float | None = None, policy: Policy | None = None, @@ -401,9 +402,9 @@ def _validate_rrsig( def _validate( - rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], - rrsigset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], - keys: Dict[dns.name.Name, dns.node.Node | dns.rdataset.Rdataset], + rrset: dns.rrset.RRset | tuple[dns.name.Name, dns.rdataset.Rdataset], + rrsigset: dns.rrset.RRset | tuple[dns.name.Name, dns.rdataset.Rdataset], + keys: dict[dns.name.Name, dns.node.Node | dns.rdataset.Rdataset], origin: dns.name.Name | None = None, now: float | None = None, policy: Policy | None = None, @@ -474,7 +475,7 @@ def _validate( def _sign( - rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], + rrset: dns.rrset.RRset | tuple[dns.name.Name, dns.rdataset.Rdataset], private_key: PrivateKey, signer: dns.name.Name, dnskey: DNSKEY, @@ -601,7 +602,7 @@ def _sign( def _make_rrsig_signature_data( - rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], + rrset: dns.rrset.RRset | tuple[dns.name.Name, dns.rdataset.Rdataset], rrsig: RRSIG, origin: dns.name.Name | None = None, ) -> bytes: @@ -802,8 +803,8 @@ def nsec3_hash( def make_ds_rdataset( - rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset], - algorithms: Set[DSDigest | str], + rrset: dns.rrset.RRset | tuple[dns.name.Name, dns.rdataset.Rdataset], + algorithms: set[DSDigest | str], origin: dns.name.Name | None = None, ) -> dns.rdataset.Rdataset: """Create a DS record from DNSKEY/CDNSKEY/CDS. @@ -952,8 +953,8 @@ def default_rrset_signer( txn: dns.transaction.Transaction, rrset: dns.rrset.RRset, signer: dns.name.Name, - ksks: List[Tuple[PrivateKey, DNSKEY]], - zsks: List[Tuple[PrivateKey, DNSKEY]], + ksks: list[tuple[PrivateKey, DNSKEY]], + zsks: list[tuple[PrivateKey, DNSKEY]], inception: datetime | str | int | float | None = None, expiration: datetime | str | int | float | None = None, lifetime: int | None = None, @@ -993,7 +994,7 @@ def default_rrset_signer( def sign_zone( zone: dns.zone.Zone, txn: dns.transaction.Transaction | None = None, - keys: List[Tuple[PrivateKey, DNSKEY]] | None = None, + keys: list[tuple[PrivateKey, DNSKEY]] | None = None, add_dnskey: bool = True, dnskey_ttl: int | None = None, inception: datetime | str | int | float | None = None, diff --git a/dns/dnssecalgs/__init__.py b/dns/dnssecalgs/__init__.py index 0810b19a..00db4b16 100644 --- a/dns/dnssecalgs/__init__.py +++ b/dns/dnssecalgs/__init__.py @@ -1,5 +1,3 @@ -from typing import Dict, Tuple, Type - import dns._features import dns.name from dns.dnssecalgs.base import GenericPrivateKey @@ -27,7 +25,7 @@ else: AlgorithmPrefix = bytes | dns.name.Name | None -algorithms: Dict[Tuple[Algorithm, AlgorithmPrefix], Type[GenericPrivateKey]] = {} +algorithms: dict[tuple[Algorithm, AlgorithmPrefix], type[GenericPrivateKey]] = {} if _have_cryptography: # pylint: disable=possibly-used-before-assignment algorithms.update( @@ -49,7 +47,7 @@ if _have_cryptography: def get_algorithm_cls( algorithm: int | str, prefix: AlgorithmPrefix = None -) -> Type[GenericPrivateKey]: +) -> type[GenericPrivateKey]: """Get Private Key class from Algorithm. *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm. @@ -67,7 +65,7 @@ def get_algorithm_cls( ) -def get_algorithm_cls_from_dnskey(dnskey: DNSKEY) -> Type[GenericPrivateKey]: +def get_algorithm_cls_from_dnskey(dnskey: DNSKEY) -> type[GenericPrivateKey]: """Get Private Key class from DNSKEY. *dnskey*, a ``DNSKEY`` to get Algorithm class for. @@ -87,7 +85,7 @@ def get_algorithm_cls_from_dnskey(dnskey: DNSKEY) -> Type[GenericPrivateKey]: def register_algorithm_cls( algorithm: int | str, - algorithm_cls: Type[GenericPrivateKey], + algorithm_cls: type[GenericPrivateKey], name: dns.name.Name | str | None = None, oid: bytes | None = None, ) -> None: diff --git a/dns/dnssecalgs/base.py b/dns/dnssecalgs/base.py index 0334fe6b..92426db7 100644 --- a/dns/dnssecalgs/base.py +++ b/dns/dnssecalgs/base.py @@ -1,5 +1,5 @@ from abc import ABC, abstractmethod # pylint: disable=no-name-in-module -from typing import Any, Type +from typing import Any import dns.rdataclass import dns.rdatatype @@ -58,7 +58,7 @@ class GenericPublicKey(ABC): class GenericPrivateKey(ABC): - public_cls: Type[GenericPublicKey] + public_cls: type[GenericPublicKey] @abstractmethod def __init__(self, key: Any) -> None: diff --git a/dns/dnssecalgs/cryptography.py b/dns/dnssecalgs/cryptography.py index 8d6876e8..710b7040 100644 --- a/dns/dnssecalgs/cryptography.py +++ b/dns/dnssecalgs/cryptography.py @@ -1,4 +1,4 @@ -from typing import Any, Type +from typing import Any from cryptography.hazmat.primitives import serialization @@ -34,7 +34,7 @@ class CryptographyPublicKey(GenericPublicKey): class CryptographyPrivateKey(GenericPrivateKey): key: Any = None key_cls: Any = None - public_cls: Type[CryptographyPublicKey] # type: ignore + public_cls: type[CryptographyPublicKey] # type: ignore def __init__(self, key: Any) -> None: # pylint: disable=super-init-not-called if self.key_cls is None: diff --git a/dns/dnssecalgs/eddsa.py b/dns/dnssecalgs/eddsa.py index 361c3dbd..77ccf02a 100644 --- a/dns/dnssecalgs/eddsa.py +++ b/dns/dnssecalgs/eddsa.py @@ -1,5 +1,3 @@ -from typing import Type - from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ed448, ed25519 @@ -27,7 +25,7 @@ class PublicEDDSA(CryptographyPublicKey): class PrivateEDDSA(CryptographyPrivateKey): - public_cls: Type[PublicEDDSA] # type: ignore + public_cls: type[PublicEDDSA] # type: ignore def sign( self, diff --git a/dns/e164.py b/dns/e164.py index 942d2c0f..5b06e6c0 100644 --- a/dns/e164.py +++ b/dns/e164.py @@ -17,7 +17,7 @@ """DNS E.164 helpers.""" -from typing import Iterable +from collections.abc import Iterable import dns.exception import dns.name diff --git a/dns/edns.py b/dns/edns.py index eb985484..1e38e14d 100644 --- a/dns/edns.py +++ b/dns/edns.py @@ -21,7 +21,7 @@ import binascii import math import socket import struct -from typing import Any, Dict +from typing import Any import dns.enum import dns.inet @@ -502,7 +502,7 @@ class ReportChannelOption(Option): return cls(parser.get_name()) -_type_to_class: Dict[OptionType, Any] = { +_type_to_class: dict[OptionType, Any] = { OptionType.ECS: ECSOption, OptionType.EDE: EDEOption, OptionType.NSID: NSIDOption, diff --git a/dns/enum.py b/dns/enum.py index 44f76afa..840a127b 100644 --- a/dns/enum.py +++ b/dns/enum.py @@ -16,7 +16,7 @@ # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import enum -from typing import Any, Type, TypeVar +from typing import Any, TypeVar TIntEnum = TypeVar("TIntEnum", bound="IntEnum") @@ -40,7 +40,7 @@ class IntEnum(enum.IntEnum): raise ValueError(f"{name} must be an int between >= 0 and <= {max}") @classmethod - def from_text(cls: Type[TIntEnum], text: str) -> TIntEnum: + def from_text(cls: type[TIntEnum], text: str) -> TIntEnum: text = text.upper() try: return cls[text] @@ -57,7 +57,7 @@ class IntEnum(enum.IntEnum): raise cls._unknown_exception_class() @classmethod - def to_text(cls: Type[TIntEnum], value: int) -> str: + def to_text(cls: type[TIntEnum], value: int) -> str: cls._check_value(value) try: text = cls(value).name @@ -69,7 +69,7 @@ class IntEnum(enum.IntEnum): return text @classmethod - def make(cls: Type[TIntEnum], value: int | str) -> TIntEnum: + def make(cls: type[TIntEnum], value: int | str) -> TIntEnum: """Convert text or a value into an enumerated type, if possible. *value*, the ``int`` or ``str`` to convert. @@ -109,5 +109,5 @@ class IntEnum(enum.IntEnum): return current_text @classmethod - def _unknown_exception_class(cls) -> Type[Exception]: + def _unknown_exception_class(cls) -> type[Exception]: return ValueError diff --git a/dns/exception.py b/dns/exception.py index c3d42ffd..8f56d156 100644 --- a/dns/exception.py +++ b/dns/exception.py @@ -22,9 +22,6 @@ always be subclasses of ``DNSException``. """ -from typing import Set - - class DNSException(Exception): """Abstract base class shared by all dnspython exceptions. @@ -49,7 +46,7 @@ class DNSException(Exception): """ msg: str | None = None # non-parametrized message - supp_kwargs: Set[str] = set() # accepted parameters for _fmt_kwargs (sanity check) + supp_kwargs: set[str] = set() # accepted parameters for _fmt_kwargs (sanity check) fmt: str | None = None # message parametrized with results from _fmt_kwargs def __init__(self, *args, **kwargs): diff --git a/dns/grange.py b/dns/grange.py index 8d366dc8..5c1bdb81 100644 --- a/dns/grange.py +++ b/dns/grange.py @@ -17,12 +17,10 @@ """DNS GENERATE range conversion.""" -from typing import Tuple - import dns.exception -def from_text(text: str) -> Tuple[int, int, int]: +def from_text(text: str) -> tuple[int, int, int]: """Convert the text form of a range in a ``$GENERATE`` statement to an integer. diff --git a/dns/inet.py b/dns/inet.py index 765203b3..985ae18a 100644 --- a/dns/inet.py +++ b/dns/inet.py @@ -18,7 +18,7 @@ """Generic Internet address helper functions.""" import socket -from typing import Any, Tuple +from typing import Any import dns.ipv4 import dns.ipv6 @@ -135,7 +135,7 @@ def is_address(text: str) -> bool: return False -def low_level_address_tuple(high_tuple: Tuple[str, int], af: int | None = None) -> Any: +def low_level_address_tuple(high_tuple: tuple[str, int], af: int | None = None) -> Any: """Given a "high-level" address tuple, i.e. an (address, port) return the appropriate "low-level" address tuple suitable for use in socket calls. diff --git a/dns/ipv6.py b/dns/ipv6.py index eaa0f6c7..b464add6 100644 --- a/dns/ipv6.py +++ b/dns/ipv6.py @@ -19,7 +19,6 @@ import binascii import re -from typing import List import dns.exception import dns.ipv4 @@ -164,7 +163,7 @@ def inet_aton(text: str | bytes, ignore_scope: bool = False) -> bytes: if l > 8: raise dns.exception.SyntaxError seen_empty = False - canonical: List[bytes] = [] + canonical: list[bytes] = [] for c in chunks: if c == b"": if seen_empty: diff --git a/dns/message.py b/dns/message.py index 30a84233..a86b9e8a 100644 --- a/dns/message.py +++ b/dns/message.py @@ -21,7 +21,7 @@ import contextlib import enum import io import time -from typing import Any, Dict, List, Tuple, cast +from typing import Any, cast import dns.edns import dns.entropy @@ -128,7 +128,7 @@ class MessageError: DEFAULT_EDNS_PAYLOAD = 1232 MAX_CHAIN = 16 -IndexKeyType = Tuple[ +IndexKeyType = tuple[ int, dns.name.Name, dns.rdataclass.RdataClass, @@ -136,8 +136,8 @@ IndexKeyType = Tuple[ dns.rdatatype.RdataType | None, dns.rdataclass.RdataClass | None, ] -IndexType = Dict[IndexKeyType, dns.rrset.RRset] -SectionType = int | str | List[dns.rrset.RRset] +IndexType = dict[IndexKeyType, dns.rrset.RRset] +SectionType = int | str | list[dns.rrset.RRset] class Message: @@ -151,7 +151,7 @@ class Message: else: self.id = id self.flags = 0 - self.sections: List[List[dns.rrset.RRset]] = [[], [], [], []] + self.sections: list[list[dns.rrset.RRset]] = [[], [], [], []] self.opt: dns.rrset.RRset | None = None self.request_payload = 0 self.pad = 0 @@ -163,12 +163,12 @@ class Message: self.origin: dns.name.Name | None = None self.tsig_ctx: Any | None = None self.index: IndexType = {} - self.errors: List[MessageError] = [] + self.errors: list[MessageError] = [] self.time = 0.0 self.wire: bytes | None = None @property - def question(self) -> List[dns.rrset.RRset]: + def question(self) -> list[dns.rrset.RRset]: """The question section.""" return self.sections[0] @@ -177,7 +177,7 @@ class Message: self.sections[0] = v @property - def answer(self) -> List[dns.rrset.RRset]: + def answer(self) -> list[dns.rrset.RRset]: """The answer section.""" return self.sections[1] @@ -186,7 +186,7 @@ class Message: self.sections[1] = v @property - def authority(self) -> List[dns.rrset.RRset]: + def authority(self) -> list[dns.rrset.RRset]: """The authority section.""" return self.sections[2] @@ -195,7 +195,7 @@ class Message: self.sections[2] = v @property - def additional(self) -> List[dns.rrset.RRset]: + def additional(self) -> list[dns.rrset.RRset]: """The additional data section.""" return self.sections[3] @@ -213,7 +213,7 @@ class Message: self, origin: dns.name.Name | None = None, relativize: bool = True, - **kw: Dict[str, Any], + **kw: dict[str, Any], ) -> str: """Convert the message to text. @@ -314,7 +314,7 @@ class Message: return False return True - def section_number(self, section: List[dns.rrset.RRset]) -> int: + def section_number(self, section: list[dns.rrset.RRset]) -> int: """Return the "section number" of the specified section for use in indexing. @@ -330,7 +330,7 @@ class Message: return self._section_enum(i) raise ValueError("unknown section") - def section_from_number(self, number: int) -> List[dns.rrset.RRset]: + def section_from_number(self, number: int) -> list[dns.rrset.RRset]: """Return the section list associated with the specified section number. @@ -566,7 +566,7 @@ class Message: tsig_ctx: Any | None = None, prepend_length: bool = False, prefer_truncation: bool = False, - **kw: Dict[str, Any], + **kw: dict[str, Any], ) -> bytes: """Return a string containing the message in DNS compressed wire format. @@ -795,7 +795,7 @@ class Message: ednsflags: int = 0, payload: int = DEFAULT_EDNS_PAYLOAD, request_payload: int | None = None, - options: List[dns.edns.Option] | None = None, + options: list[dns.edns.Option] | None = None, pad: int = 0, ) -> None: """Configure EDNS behavior. @@ -872,7 +872,7 @@ class Message: return 0 @property - def options(self) -> Tuple: + def options(self) -> tuple: if self.opt: rdata = cast(dns.rdtypes.ANY.OPT.OPT, self.opt[0]) return rdata.options @@ -926,13 +926,13 @@ class Message: self.flags &= 0x87FF self.flags |= dns.opcode.to_flags(opcode) - def get_options(self, otype: dns.edns.OptionType) -> List[dns.edns.Option]: + def get_options(self, otype: dns.edns.OptionType) -> list[dns.edns.Option]: """Return the list of options of the specified type.""" return [option for option in self.options if option.otype == otype] - def extended_errors(self) -> List[dns.edns.EDEOption]: + def extended_errors(self) -> list[dns.edns.EDEOption]: """Return the list of Extended DNS Error (EDE) options in the message""" - return cast(List[dns.edns.EDEOption], self.get_options(dns.edns.OptionType.EDE)) + return cast(list[dns.edns.EDEOption], self.get_options(dns.edns.OptionType.EDE)) def _get_one_rr_per_rrset(self, value): # What the caller picked is fine. @@ -987,7 +987,7 @@ class ChainingResult: canonical_name: dns.name.Name, answer: dns.rrset.RRset | None, minimum_ttl: int, - cnames: List[dns.rrset.RRset], + cnames: list[dns.rrset.RRset], ): self.canonical_name = canonical_name self.answer = answer @@ -1756,7 +1756,7 @@ def make_query( ednsflags: int | None = None, payload: int | None = None, request_payload: int | None = None, - options: List[dns.edns.Option] | None = None, + options: list[dns.edns.Option] | None = None, idna_codec: dns.name.IDNACodec | None = None, id: int | None = None, flags: int = dns.flags.RD, @@ -1827,7 +1827,7 @@ def make_query( # only pass keywords on to use_edns if they have been set to a # non-None value. Setting a field will turn EDNS on if it hasn't # been configured. - kwargs: Dict[str, Any] = {} + kwargs: dict[str, Any] = {} if ednsflags is not None: kwargs["ednsflags"] = ednsflags if payload is not None: diff --git a/dns/name.py b/dns/name.py index 5af55839..53f08c7e 100644 --- a/dns/name.py +++ b/dns/name.py @@ -21,7 +21,8 @@ import copy import encodings.idna # type: ignore import functools import struct -from typing import Any, Callable, Dict, Iterable, Optional, Tuple +from collections.abc import Callable, Iterable +from typing import Any import dns._features import dns.enum @@ -42,7 +43,7 @@ else: # pragma: no cover have_idna_2008 = False -CompressType = Dict["Name", int] +CompressType = dict["Name", int] class NameRelation(dns.enum.IntEnum): @@ -317,7 +318,7 @@ IDNA_2008_Transitional = IDNA2008Codec(True, True, False, False) IDNA_2008 = IDNA_2008_Practical -def _validate_labels(labels: Tuple[bytes, ...]) -> None: +def _validate_labels(labels: tuple[bytes, ...]) -> None: """Check for empty labels in the middle of a label sequence, labels that are too long, and for too many labels. @@ -420,7 +421,7 @@ class Name: h += (h << 3) + c return h - def fullcompare(self, other: "Name") -> Tuple[NameRelation, int, int]: + def fullcompare(self, other: "Name") -> tuple[NameRelation, int, int]: """Compare two names, returning a 3-tuple ``(relation, order, nlabels)``. @@ -626,7 +627,7 @@ class Name: idna_codec = IDNA_2003_Practical return ".".join([idna_codec.decode(x) for x in l]) - def to_digestable(self, origin: Optional["Name"] = None) -> bytes: + def to_digestable(self, origin: "Name | None" = None) -> bytes: """Convert name to a format suitable for digesting in hashes. The name is canonicalized and converted to uncompressed wire @@ -651,7 +652,7 @@ class Name: self, file: Any | None = None, compress: CompressType | None = None, - origin: Optional["Name"] = None, + origin: "Name | None" = None, canonicalize: bool = False, ) -> bytes | None: """Convert name to wire format, possibly compressing it. @@ -751,7 +752,7 @@ class Name: def __sub__(self, other): return self.relativize(other) - def split(self, depth: int) -> Tuple["Name", "Name"]: + def split(self, depth: int) -> tuple["Name", "Name"]: """Split a name into a prefix and suffix names at the specified depth. *depth* is an ``int`` specifying the number of labels in the suffix @@ -819,7 +820,7 @@ class Name: return self def choose_relativity( - self, origin: Optional["Name"] = None, relativize: bool = True + self, origin: "Name | None" = None, relativize: bool = True ) -> "Name": """Return a name with the relativity desired by the caller. @@ -1105,7 +1106,7 @@ def from_wire_parser(parser: "dns.wire.Parser") -> Name: return Name(labels) -def from_wire(message: bytes, current: int) -> Tuple[Name, int]: +def from_wire(message: bytes, current: int) -> tuple[Name, int]: """Convert possibly compressed wire format into a Name. *message* is a ``bytes`` containing an entire DNS message in DNS diff --git a/dns/node.py b/dns/node.py index b2cbf1b2..caeebd5b 100644 --- a/dns/node.py +++ b/dns/node.py @@ -19,7 +19,7 @@ import enum import io -from typing import Any, Dict +from typing import Any import dns.immutable import dns.name @@ -90,7 +90,7 @@ class Node: # the set of rdatasets, represented as a list. self.rdatasets = [] - def to_text(self, name: dns.name.Name, **kw: Dict[str, Any]) -> str: + def to_text(self, name: dns.name.Name, **kw: dict[str, Any]) -> str: """Convert a node to text format. Each rdataset at the node is printed. Any keyword arguments diff --git a/dns/opcode.py b/dns/opcode.py index 3fa610d0..4aac2586 100644 --- a/dns/opcode.py +++ b/dns/opcode.py @@ -17,8 +17,6 @@ """DNS Opcodes.""" -from typing import Type - import dns.enum import dns.exception @@ -40,7 +38,7 @@ class Opcode(dns.enum.IntEnum): return 15 @classmethod - def _unknown_exception_class(cls) -> Type[Exception]: + def _unknown_exception_class(cls) -> type[Exception]: return UnknownOpcode diff --git a/dns/query.py b/dns/query.py index 64a2e2d7..bac51746 100644 --- a/dns/query.py +++ b/dns/query.py @@ -28,7 +28,8 @@ import socket import struct import time import urllib.parse -from typing import Any, Callable, Dict, Optional, Tuple, cast +from collections.abc import Callable +from typing import Any, cast import dns._features import dns._tls_util @@ -411,7 +412,7 @@ def _make_socket( def _maybe_get_resolver( - resolver: Optional["dns.resolver.Resolver"], # type: ignore + resolver: "dns.resolver.Resolver | None", # type: ignore ) -> "dns.resolver.Resolver": # type: ignore # We need a separate method for this to avoid overriding the global # variable "dns" with the as-yet undefined local variable "dns" @@ -454,7 +455,7 @@ def https( post: bool = True, bootstrap_address: str | None = None, verify: bool | str | ssl.SSLContext = True, - resolver: Optional["dns.resolver.Resolver"] = None, # type: ignore + resolver: "dns.resolver.Resolver | None" = None, # type: ignore family: int = socket.AF_UNSPEC, http_version: HTTPVersion = HTTPVersion.DEFAULT, ) -> dns.message.Message: @@ -766,7 +767,7 @@ def send_udp( what: dns.message.Message | bytes, destination: Any, expiration: float | None = None, -) -> Tuple[int, float]: +) -> tuple[int, float]: """Send a DNS message to the specified UDP socket. *sock*, a ``socket``. @@ -796,7 +797,7 @@ def receive_udp( expiration: float | None = None, ignore_unexpected: bool = False, one_rr_per_rrset: bool = False, - keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, + keyring: dict[dns.name.Name, dns.tsig.Key] | None = None, request_mac: bytes | None = b"", ignore_trailing: bool = False, raise_on_truncation: bool = False, @@ -1001,7 +1002,7 @@ def udp_with_fallback( udp_sock: Any | None = None, tcp_sock: Any | None = None, ignore_errors: bool = False, -) -> Tuple[dns.message.Message, bool]: +) -> tuple[dns.message.Message, bool]: """Return the response to the query, trying UDP first and falling back to TCP if UDP results in a truncated response. @@ -1117,7 +1118,7 @@ def send_tcp( sock: Any, what: dns.message.Message | bytes, expiration: float | None = None, -) -> Tuple[int, float]: +) -> tuple[int, float]: """Send a DNS message to the specified TCP socket. *sock*, a ``socket``. @@ -1147,10 +1148,10 @@ def receive_tcp( sock: Any, expiration: float | None = None, one_rr_per_rrset: bool = False, - keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, + keyring: dict[dns.name.Name, dns.tsig.Key] | None = None, request_mac: bytes | None = b"", ignore_trailing: bool = False, -) -> Tuple[dns.message.Message, float]: +) -> tuple[dns.message.Message, float]: """Read a DNS message from a TCP socket. *sock*, a ``socket``. @@ -1494,7 +1495,7 @@ def quic( q.id = 0 wire = q.to_wire() the_connection: dns.quic.SyncQuicConnection - the_manager: dns.quic.SyncQuicManager # type: ignore + the_manager: dns.quic.SyncQuicManager # type: ignore if connection: manager: contextlib.AbstractContextManager = contextlib.nullcontext(None) the_connection = connection @@ -1599,7 +1600,7 @@ def xfr( rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, timeout: float | None = None, port: int = 53, - keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, + keyring: dict[dns.name.Name, dns.tsig.Key] | None = None, keyname: dns.name.Name | str | None = None, relativize: bool = True, lifetime: float | None = None, diff --git a/dns/quic/__init__.py b/dns/quic/__init__.py index da8d2980..ce672772 100644 --- a/dns/quic/__init__.py +++ b/dns/quic/__init__.py @@ -1,6 +1,6 @@ # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license -from typing import Any, Dict, List, Tuple +from typing import Any import dns._features import dns.asyncbackend @@ -32,7 +32,7 @@ if dns._features.have("doq"): # We have a context factory and a manager factory as for trio we need to have # a nursery. - _async_factories: Dict[str, Tuple[Any, Any]] = { + _async_factories: dict[str, tuple[Any, Any]] = { "asyncio": (null_factory, _asyncio_manager_factory) } @@ -75,4 +75,4 @@ else: # pragma: no cover raise NotImplementedError -Headers = List[Tuple[bytes, bytes]] +Headers = list[tuple[bytes, bytes]] diff --git a/dns/quic/_asyncio.py b/dns/quic/_asyncio.py index 0a177b67..3d6df43c 100644 --- a/dns/quic/_asyncio.py +++ b/dns/quic/_asyncio.py @@ -6,10 +6,7 @@ import ssl import struct import time -import aioquic.h3.connection # type: ignore import aioquic.h3.events # type: ignore -import aioquic.quic.configuration # type: ignore -import aioquic.quic.connection # type: ignore import aioquic.quic.events # type: ignore import dns.asyncbackend diff --git a/dns/quic/_sync.py b/dns/quic/_sync.py index 18f9d05b..aad00f7f 100644 --- a/dns/quic/_sync.py +++ b/dns/quic/_sync.py @@ -7,10 +7,7 @@ import struct import threading import time -import aioquic.h3.connection # type: ignore import aioquic.h3.events # type: ignore -import aioquic.quic.configuration # type: ignore -import aioquic.quic.connection # type: ignore import aioquic.quic.events # type: ignore import dns.exception diff --git a/dns/quic/_trio.py b/dns/quic/_trio.py index c4dcc98d..317f630e 100644 --- a/dns/quic/_trio.py +++ b/dns/quic/_trio.py @@ -5,10 +5,7 @@ import ssl import struct import time -import aioquic.h3.connection # type: ignore import aioquic.h3.events # type: ignore -import aioquic.quic.configuration # type: ignore -import aioquic.quic.connection # type: ignore import aioquic.quic.events # type: ignore import trio diff --git a/dns/rcode.py b/dns/rcode.py index 7bb8467e..0314dea0 100644 --- a/dns/rcode.py +++ b/dns/rcode.py @@ -17,8 +17,6 @@ """DNS Result Codes.""" -from typing import Tuple, Type - import dns.enum import dns.exception @@ -72,7 +70,7 @@ class Rcode(dns.enum.IntEnum): return 4095 @classmethod - def _unknown_exception_class(cls) -> Type[Exception]: + def _unknown_exception_class(cls) -> type[Exception]: return UnknownRcode @@ -109,7 +107,7 @@ def from_flags(flags: int, ednsflags: int) -> Rcode: return Rcode.make(value) -def to_flags(value: Rcode) -> Tuple[int, int]: +def to_flags(value: Rcode) -> tuple[int, int]: """Return a (flags, ednsflags) tuple which encodes the rcode. *value*, a ``dns.rcode.Rcode``, the rcode. diff --git a/dns/rdata.py b/dns/rdata.py index 4a162cb9..5e701a34 100644 --- a/dns/rdata.py +++ b/dns/rdata.py @@ -25,7 +25,7 @@ import ipaddress import itertools import random from importlib import import_module -from typing import Any, Dict, Tuple +from typing import Any import dns.exception import dns.immutable @@ -204,7 +204,7 @@ class Rdata: self, origin: dns.name.Name | None = None, relativize: bool = True, - **kw: Dict[str, Any], + **kw: dict[str, Any], ) -> str: """Convert an rdata to text format. @@ -633,7 +633,7 @@ class GenericRdata(Rdata): self, origin: dns.name.Name | None = None, relativize: bool = True, - **kw: Dict[str, Any], + **kw: dict[str, Any], ) -> str: return rf"\# {len(self.data)} " + _hexify(self.data, **kw) # type: ignore @@ -662,7 +662,7 @@ class GenericRdata(Rdata): return cls(rdclass, rdtype, parser.get_remaining()) -_rdata_classes: Dict[Tuple[dns.rdataclass.RdataClass, dns.rdatatype.RdataType], Any] = ( +_rdata_classes: dict[tuple[dns.rdataclass.RdataClass, dns.rdatatype.RdataType], Any] = ( {} ) _module_prefix = "dns.rdtypes" diff --git a/dns/rdataset.py b/dns/rdataset.py index 19191fcc..63e72ea7 100644 --- a/dns/rdataset.py +++ b/dns/rdataset.py @@ -20,7 +20,8 @@ import io import random import struct -from typing import Any, Collection, Dict, List, cast +from collections.abc import Collection +from typing import Any, cast import dns.exception import dns.immutable @@ -201,7 +202,7 @@ class Rdataset(dns.set.Set): relativize: bool = True, override_rdclass: dns.rdataclass.RdataClass | None = None, want_comments: bool = False, - **kw: Dict[str, Any], + **kw: dict[str, Any], ) -> str: """Convert the rdataset into DNS zone file format. @@ -311,7 +312,7 @@ class Rdataset(dns.set.Set): file.write(struct.pack("!HHIH", self.rdtype, rdclass, 0, 0)) return 1 else: - l: Rdataset | List[dns.rdata.Rdata] + l: Rdataset | list[dns.rdata.Rdata] if want_shuffle: l = list(self) random.shuffle(l) @@ -337,7 +338,7 @@ class Rdataset(dns.set.Set): return True return False - def processing_order(self) -> List[dns.rdata.Rdata]: + def processing_order(self) -> list[dns.rdata.Rdata]: """Return rdatas in a valid processing order according to the type's specification. For example, MX records are in preference order from lowest to highest preferences, with items of the same preference diff --git a/dns/rdatatype.py b/dns/rdatatype.py index 211d810d..88a77761 100644 --- a/dns/rdatatype.py +++ b/dns/rdatatype.py @@ -17,8 +17,6 @@ """DNS Rdata Types.""" -from typing import Dict - import dns.enum import dns.exception @@ -145,8 +143,8 @@ class RdataType(dns.enum.IntEnum): return UnknownRdatatype -_registered_by_text: Dict[str, RdataType] = {} -_registered_by_value: Dict[RdataType, str] = {} +_registered_by_text: dict[str, RdataType] = {} +_registered_by_value: dict[RdataType, str] = {} _metatypes = {RdataType.OPT} diff --git a/dns/rdtypes/svcbbase.py b/dns/rdtypes/svcbbase.py index 7338b664..bf7570f0 100644 --- a/dns/rdtypes/svcbbase.py +++ b/dns/rdtypes/svcbbase.py @@ -3,14 +3,13 @@ import base64 import enum import struct -from typing import Any, Dict +from typing import Any import dns.enum import dns.exception import dns.immutable import dns.ipv4 import dns.ipv6 -import dns.name import dns.rdata import dns.rdtypes.util import dns.renderer @@ -428,7 +427,7 @@ class OHTTPParam(Param): raise NotImplementedError # pragma: no cover -_class_for_key: Dict[ParamKey, Any] = { +_class_for_key: dict[ParamKey, Any] = { ParamKey.MANDATORY: MandatoryParam, ParamKey.ALPN: ALPNParam, ParamKey.NO_DEFAULT_ALPN: NoDefaultALPNParam, diff --git a/dns/rdtypes/txtbase.py b/dns/rdtypes/txtbase.py index 5e5b24f5..b10da13b 100644 --- a/dns/rdtypes/txtbase.py +++ b/dns/rdtypes/txtbase.py @@ -17,7 +17,8 @@ """TXT-like base class.""" -from typing import Any, Dict, Iterable, Tuple +from collections.abc import Iterable +from typing import Any import dns.exception import dns.immutable @@ -50,7 +51,7 @@ class TXTBase(dns.rdata.Rdata): *strings*, a tuple of ``bytes`` """ super().__init__(rdclass, rdtype) - self.strings: Tuple[bytes] = self._as_tuple( + self.strings: tuple[bytes] = self._as_tuple( strings, lambda x: self._as_bytes(x, True, 255) ) if len(self.strings) == 0: @@ -60,7 +61,7 @@ class TXTBase(dns.rdata.Rdata): self, origin: dns.name.Name | None = None, relativize: bool = True, - **kw: Dict[str, Any], + **kw: dict[str, Any], ) -> str: txt = "" prefix = "" diff --git a/dns/rdtypes/util.py b/dns/rdtypes/util.py index e1730db5..5516f264 100644 --- a/dns/rdtypes/util.py +++ b/dns/rdtypes/util.py @@ -18,7 +18,8 @@ import collections import random import struct -from typing import Any, Iterable, List, Tuple +from collections.abc import Iterable +from typing import Any import dns.exception import dns.ipv4 @@ -126,7 +127,7 @@ class Bitmap: type_name = "" - def __init__(self, windows: Iterable[Tuple[int, bytes]] | None = None): + def __init__(self, windows: Iterable[tuple[int, bytes]] | None = None): last_window = -1 if windows is None: windows = [] @@ -167,7 +168,7 @@ class Bitmap: return cls.from_rdtypes(rdtypes) @classmethod - def from_rdtypes(cls, rdtypes: List[dns.rdatatype.RdataType]) -> "Bitmap": + def from_rdtypes(cls, rdtypes: list[dns.rdatatype.RdataType]) -> "Bitmap": rdtypes = sorted(rdtypes) window = 0 octets = 0 diff --git a/dns/resolver.py b/dns/resolver.py index 2b908a45..c9825f75 100644 --- a/dns/resolver.py +++ b/dns/resolver.py @@ -24,7 +24,8 @@ import sys import threading import time import warnings -from typing import Any, Dict, Iterator, List, Sequence, Tuple, cast +from collections.abc import Iterator, Sequence +from typing import Any, cast from urllib.parse import urlparse import dns._ddr @@ -143,7 +144,7 @@ class YXDOMAIN(dns.exception.DNSException): """The DNS query name is too long after DNAME substitution.""" -ErrorTuple = Tuple[ +ErrorTuple = tuple[ str | None, bool, int, @@ -152,7 +153,7 @@ ErrorTuple = Tuple[ ] -def _errors_to_text(errors: List[ErrorTuple]) -> List[str]: +def _errors_to_text(errors: list[ErrorTuple]) -> list[str]: """Turn a resolution errors trace into a list of text.""" texts = [] for err in errors: @@ -345,7 +346,7 @@ class HostAnswers(Answers): # filtering by address family. def addresses_and_families( self, family: int = socket.AF_UNSPEC - ) -> Iterator[Tuple[str, int]]: + ) -> Iterator[tuple[str, int]]: if family == socket.AF_UNSPEC: yield from self.addresses_and_families(socket.AF_INET6) yield from self.addresses_and_families(socket.AF_INET) @@ -419,7 +420,7 @@ class CacheBase: return self.statistics.clone() -CacheKey = Tuple[dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass] +CacheKey = tuple[dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass] class Cache(CacheBase): @@ -431,7 +432,7 @@ class Cache(CacheBase): """ super().__init__() - self.data: Dict[CacheKey, Answer] = {} + self.data: dict[CacheKey, Answer] = {} self.cleaning_interval = cleaning_interval self.next_cleaning: float = time.time() + self.cleaning_interval @@ -538,7 +539,7 @@ class LRUCache(CacheBase): """ super().__init__() - self.data: Dict[CacheKey, LRUCacheNode] = {} + self.data: dict[CacheKey, LRUCacheNode] = {} self.set_max_size(max_size) self.sentinel: LRUCacheNode = LRUCacheNode(None, None) self.sentinel.prev = self.sentinel @@ -670,12 +671,12 @@ class _Resolution: self.rdclass = rdclass self.tcp = tcp self.raise_on_no_answer = raise_on_no_answer - self.nxdomain_responses: Dict[dns.name.Name, dns.message.QueryMessage] = {} + self.nxdomain_responses: dict[dns.name.Name, dns.message.QueryMessage] = {} # Initialize other things to help analysis tools self.qname = dns.name.empty - self.nameservers: List[dns.nameserver.Nameserver] = [] - self.current_nameservers: List[dns.nameserver.Nameserver] = [] - self.errors: List[ErrorTuple] = [] + self.nameservers: list[dns.nameserver.Nameserver] = [] + self.current_nameservers: list[dns.nameserver.Nameserver] = [] + self.errors: list[ErrorTuple] = [] self.nameserver: dns.nameserver.Nameserver | None = None self.tcp_attempt = False self.retry_with_tcp = False @@ -684,7 +685,7 @@ class _Resolution: def next_request( self, - ) -> Tuple[dns.message.QueryMessage | None, Answer | None]: + ) -> tuple[dns.message.QueryMessage | None, Answer | None]: """Get the next request to send, and check the cache. Returns a (request, answer) tuple. At most one of request or @@ -757,7 +758,7 @@ class _Resolution: # raise NXDOMAIN(qnames=self.qnames_to_try, responses=self.nxdomain_responses) - def next_nameserver(self) -> Tuple[dns.nameserver.Nameserver, bool, float]: + def next_nameserver(self) -> tuple[dns.nameserver.Nameserver, bool, float]: if self.retry_with_tcp: assert self.nameserver is not None assert not self.nameserver.is_always_max_size() @@ -780,7 +781,7 @@ class _Resolution: def query_result( self, response: dns.message.Message | None, ex: Exception | None - ) -> Tuple[Answer | None, bool]: + ) -> tuple[Answer | None, bool]: # # returns an (answer: Answer, end_loop: bool) tuple. # @@ -911,9 +912,9 @@ class BaseResolver: # pylint: disable=attribute-defined-outside-init domain: dns.name.Name - nameserver_ports: Dict[str, int] + nameserver_ports: dict[str, int] port: int - search: List[dns.name.Name] + search: list[dns.name.Name] use_search_by_default: bool timeout: float lifetime: float @@ -922,7 +923,7 @@ class BaseResolver: keyalgorithm: dns.name.Name | str edns: int ednsflags: int - ednsoptions: List[dns.edns.Option] | None + ednsoptions: list[dns.edns.Option] | None payload: int cache: Any flags: int | None @@ -1065,7 +1066,7 @@ class BaseResolver: self, start: float, lifetime: float | None = None, - errors: List[ErrorTuple] | None = None, + errors: list[ErrorTuple] | None = None, ) -> float: lifetime = self.lifetime if lifetime is None else lifetime now = time.time() @@ -1087,7 +1088,7 @@ class BaseResolver: def _get_qnames_to_try( self, qname: dns.name.Name, search: bool | None - ) -> List[dns.name.Name]: + ) -> list[dns.name.Name]: # This is a separate method so we can unit test the search # rules without requiring the Internet. if search is None: @@ -1147,7 +1148,7 @@ class BaseResolver: edns: int | bool | None = 0, ednsflags: int = 0, payload: int = dns.message.DEFAULT_EDNS_PAYLOAD, - options: List[dns.edns.Option] | None = None, + options: list[dns.edns.Option] | None = None, ) -> None: """Configure EDNS behavior. @@ -1187,9 +1188,9 @@ class BaseResolver: def _enrich_nameservers( cls, nameservers: Sequence[str | dns.nameserver.Nameserver], - nameserver_ports: Dict[str, int], + nameserver_ports: dict[str, int], default_port: int, - ) -> List[dns.nameserver.Nameserver]: + ) -> list[dns.nameserver.Nameserver]: enriched_nameservers = [] if isinstance(nameservers, list | tuple): for nameserver in nameservers: @@ -1397,7 +1398,7 @@ class Resolver(BaseResolver): # We make a modified kwargs for type checking happiness, as otherwise # we get a legit warning about possibly having rdtype and rdclass # in the kwargs more than once. - modified_kwargs: Dict[str, Any] = {} + modified_kwargs: dict[str, Any] = {} modified_kwargs.update(kwargs) modified_kwargs["rdtype"] = dns.rdatatype.PTR modified_kwargs["rdclass"] = dns.rdataclass.IN @@ -1428,7 +1429,7 @@ class Resolver(BaseResolver): # We make a modified kwargs for type checking happiness, as otherwise # we get a legit warning about possibly having rdtype and rdclass # in the kwargs more than once. - modified_kwargs: Dict[str, Any] = {} + modified_kwargs: dict[str, Any] = {} modified_kwargs.update(kwargs) modified_kwargs.pop("rdtype", None) modified_kwargs["rdclass"] = dns.rdataclass.IN @@ -1768,7 +1769,7 @@ def make_resolver_at( """ if resolver is None: resolver = get_default_resolver() - nameservers: List[str | dns.nameserver.Nameserver] = [] + nameservers: list[str | dns.nameserver.Nameserver] = [] if isinstance(where, str) and dns.inet.is_address(where): nameservers.append(dns.nameserver.Do53Nameserver(where, port)) else: @@ -1825,7 +1826,7 @@ def resolve_at( # running process. # -_protocols_for_socktype: Dict[Any, List[Any]] = { +_protocols_for_socktype: dict[Any, list[Any]] = { socket.SOCK_DGRAM: [socket.SOL_UDP], socket.SOCK_STREAM: [socket.SOL_TCP], } diff --git a/dns/rrset.py b/dns/rrset.py index 271ddbe8..5ac00ce5 100644 --- a/dns/rrset.py +++ b/dns/rrset.py @@ -17,14 +17,14 @@ """DNS RRsets (an RRset is a named rdataset)""" -from typing import Any, Collection, Dict, cast +from collections.abc import Collection +from typing import Any, cast import dns.name import dns.rdata import dns.rdataclass import dns.rdataset import dns.rdatatype -import dns.renderer class RRset(dns.rdataset.Rdataset): @@ -133,7 +133,7 @@ class RRset(dns.rdataset.Rdataset): self, origin: dns.name.Name | None = None, relativize: bool = True, - **kw: Dict[str, Any], + **kw: dict[str, Any], ) -> str: """Convert the RRset into DNS zone file format. @@ -160,7 +160,7 @@ class RRset(dns.rdataset.Rdataset): file: Any, compress: dns.name.CompressType | None = None, # type: ignore origin: dns.name.Name | None = None, - **kw: Dict[str, Any], + **kw: dict[str, Any], ) -> int: """Convert the RRset to wire format. diff --git a/dns/tokenizer.py b/dns/tokenizer.py index b1584ae5..175764af 100644 --- a/dns/tokenizer.py +++ b/dns/tokenizer.py @@ -19,7 +19,7 @@ import io import sys -from typing import Any, List, Tuple +from typing import Any import dns.exception import dns.name @@ -294,7 +294,7 @@ class Tokenizer: self.ungotten_char = None return c - def where(self) -> Tuple[str, int]: + def where(self) -> tuple[str, int]: """Return the current location in the input. Returns a (string, int) tuple. The first item is the filename of @@ -502,7 +502,6 @@ class Tokenizer: Returns an int. """ - return self.as_uint8(self.get().unescape()) def get_uint16(self, base: int = 10) -> int: @@ -560,7 +559,7 @@ class Tokenizer: return self.as_identifier(self.get().unescape()) - def get_remaining(self, max_tokens: int | None = None) -> List[Token]: + def get_remaining(self, max_tokens: int | None = None) -> list[Token]: """Return the remaining tokens on the line, until an EOL or EOF is seen. max_tokens: If not None, stop after this number of tokens. diff --git a/dns/transaction.py b/dns/transaction.py index 9ecd7377..96a36b01 100644 --- a/dns/transaction.py +++ b/dns/transaction.py @@ -1,7 +1,8 @@ # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license import collections -from typing import Any, Callable, Iterator, List, Tuple +from collections.abc import Callable, Iterator +from typing import Any import dns.exception import dns.name @@ -32,7 +33,7 @@ class TransactionManager: def origin_information( self, - ) -> Tuple[dns.name.Name | None, bool, dns.name.Name | None]: + ) -> tuple[dns.name.Name | None, bool, dns.name.Name | None]: """Returns a tuple (absolute_origin, relativize, effective_origin) @@ -115,15 +116,15 @@ class Transaction: self.replacement = replacement self.read_only = read_only self._ended = False - self._check_put_rdataset: List[CheckPutRdatasetType] = [] - self._check_delete_rdataset: List[CheckDeleteRdatasetType] = [] - self._check_delete_name: List[CheckDeleteNameType] = [] + self._check_put_rdataset: list[CheckPutRdatasetType] = [] + self._check_delete_rdataset: list[CheckDeleteRdatasetType] = [] + self._check_delete_name: list[CheckDeleteNameType] = [] # # This is the high level API # # Note that we currently use non-immutable types in the return type signature to - # avoid covariance problems, e.g. if the caller has a List[Rdataset], mypy will be + # avoid covariance problems, e.g. if the caller has a list[Rdataset], mypy will be # unhappy if we return an ImmutableRdataset. def get( @@ -359,7 +360,7 @@ class Transaction: def iterate_rdatasets( self, - ) -> Iterator[Tuple[dns.name.Name, dns.rdataset.Rdataset]]: + ) -> Iterator[tuple[dns.name.Name, dns.rdataset.Rdataset]]: """Iterate all the rdatasets in the transaction, returning (`dns.name.Name`, `dns.rdataset.Rdataset`) tuples. diff --git a/dns/tsigkeyring.py b/dns/tsigkeyring.py index 5996295a..0de4f601 100644 --- a/dns/tsigkeyring.py +++ b/dns/tsigkeyring.py @@ -18,20 +18,20 @@ """A place to store TSIG keys.""" import base64 -from typing import Any, Dict +from typing import Any import dns.name import dns.tsig -def from_text(textring: Dict[str, Any]) -> Dict[dns.name.Name, Any]: +def from_text(textring: dict[str, Any]) -> dict[dns.name.Name, Any]: """Convert a dictionary containing (textual DNS name, base64 secret) pairs into a binary keyring which has (dns.name.Name, bytes) pairs, or a dictionary containing (textual DNS name, (algorithm, base64 secret)) pairs into a binary keyring which has (dns.name.Name, dns.tsig.Key) pairs. @rtype: dict""" - keyring: Dict[dns.name.Name, Any] = {} + keyring: dict[dns.name.Name, Any] = {} for name, value in textring.items(): kname = dns.name.from_text(name) if isinstance(value, str): @@ -42,7 +42,7 @@ def from_text(textring: Dict[str, Any]) -> Dict[dns.name.Name, Any]: return keyring -def to_text(keyring: Dict[dns.name.Name, Any]) -> Dict[str, Any]: +def to_text(keyring: dict[dns.name.Name, Any]) -> dict[str, Any]: """Convert a dictionary containing (dns.name.Name, dns.tsig.Key) pairs into a text keyring which has (textual DNS name, (textual algorithm, base64 secret)) pairs, or a dictionary containing (dns.name.Name, bytes) diff --git a/dns/update.py b/dns/update.py index 41370ac7..93e9d48c 100644 --- a/dns/update.py +++ b/dns/update.py @@ -17,7 +17,7 @@ """DNS Dynamic Update Support""" -from typing import Any, List +from typing import Any import dns.enum import dns.exception @@ -93,7 +93,7 @@ class UpdateMessage(dns.message.Message): # lgtm[py/missing-equals] self.use_tsig(keyring, keyname, algorithm=keyalgorithm) @property - def zone(self) -> List[dns.rrset.RRset]: + def zone(self) -> list[dns.rrset.RRset]: """The zone section.""" return self.sections[0] @@ -102,7 +102,7 @@ class UpdateMessage(dns.message.Message): # lgtm[py/missing-equals] self.sections[0] = v @property - def prerequisite(self) -> List[dns.rrset.RRset]: + def prerequisite(self) -> list[dns.rrset.RRset]: """The prerequisite section.""" return self.sections[1] @@ -111,7 +111,7 @@ class UpdateMessage(dns.message.Message): # lgtm[py/missing-equals] self.sections[1] = v @property - def update(self) -> List[dns.rrset.RRset]: + def update(self) -> list[dns.rrset.RRset]: """The update section.""" return self.sections[2] diff --git a/dns/versioned.py b/dns/versioned.py index 28d1d41e..a2c4b2aa 100644 --- a/dns/versioned.py +++ b/dns/versioned.py @@ -4,7 +4,8 @@ import collections import threading -from typing import Callable, Deque, Set, cast +from collections.abc import Callable +from typing import cast import dns.exception import dns.name @@ -65,7 +66,7 @@ class Zone(dns.zone.Zone): # lgtm[py/missing-equals] the default policy, which retains one version is used. """ super().__init__(origin, rdclass, relativize) - self._versions: Deque[Version] = collections.deque() + self._versions: collections.deque[Version] = collections.deque() self._version_lock = threading.Lock() if pruning_policy is None: self._pruning_policy = self._default_pruning_policy @@ -73,8 +74,8 @@ class Zone(dns.zone.Zone): # lgtm[py/missing-equals] self._pruning_policy = pruning_policy self._write_txn: Transaction | None = None self._write_event: threading.Event | None = None - self._write_waiters: Deque[threading.Event] = collections.deque() - self._readers: Set[Transaction] = set() + self._write_waiters: collections.deque[threading.Event] = collections.deque() + self._readers: set[Transaction] = set() self._commit_version_unlocked( None, WritableVersion(self, replacement=True), origin ) diff --git a/dns/wire.py b/dns/wire.py index cd027fa1..ec06b196 100644 --- a/dns/wire.py +++ b/dns/wire.py @@ -2,7 +2,7 @@ import contextlib import struct -from typing import Iterator, Optional, Tuple +from collections.abc import Iterator import dns.exception import dns.name @@ -57,10 +57,10 @@ class Parser: def get_uint48(self) -> int: return int.from_bytes(self.get_bytes(6), "big") - def get_struct(self, format: str) -> Tuple: + def get_struct(self, format: str) -> tuple: return struct.unpack(format, self.get_bytes(struct.calcsize(format))) - def get_name(self, origin: Optional["dns.name.Name"] = None) -> "dns.name.Name": + def get_name(self, origin: "dns.name.Name | None" = None) -> "dns.name.Name": name = dns.name.from_wire_parser(self) if origin: name = name.relativize(origin) diff --git a/dns/xfr.py b/dns/xfr.py index 5f21fea8..451d9882 100644 --- a/dns/xfr.py +++ b/dns/xfr.py @@ -15,7 +15,7 @@ # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -from typing import Any, List, Tuple, cast +from typing import Any, cast import dns.edns import dns.exception @@ -27,13 +27,10 @@ import dns.rdataset import dns.rdatatype import dns.rdtypes import dns.rdtypes.ANY -import dns.rdtypes.ANY.SMIMEA import dns.rdtypes.ANY.SOA -import dns.rdtypes.svcbbase import dns.serial import dns.transaction import dns.tsig -import dns.zone class TransferError(dns.exception.DNSException): @@ -274,11 +271,11 @@ def make_query( ednsflags: int | None = None, payload: int | None = None, request_payload: int | None = None, - options: List[dns.edns.Option] | None = None, + options: list[dns.edns.Option] | None = None, keyring: Any = None, keyname: dns.name.Name | None = None, keyalgorithm: dns.name.Name | str = dns.tsig.default_algorithm, -) -> Tuple[dns.message.QueryMessage, int | None]: +) -> tuple[dns.message.QueryMessage, int | None]: """Make an AXFR or IXFR query. *txn_manager* is a ``dns.transaction.TransactionManager``, typically a diff --git a/dns/zone.py b/dns/zone.py index b71f244d..cc056c80 100644 --- a/dns/zone.py +++ b/dns/zone.py @@ -21,17 +21,8 @@ import contextlib import io import os import struct -from typing import ( - Any, - Callable, - Iterable, - Iterator, - List, - MutableMapping, - Set, - Tuple, - cast, -) +from collections.abc import Callable, Iterable, Iterator, MutableMapping +from typing import Any, cast import dns.exception import dns.immutable @@ -560,7 +551,7 @@ class Zone(dns.transaction.TransactionManager): self, rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.ANY, covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - ) -> Iterator[Tuple[dns.name.Name, dns.rdataset.Rdataset]]: + ) -> Iterator[tuple[dns.name.Name, dns.rdataset.Rdataset]]: """Return a generator which yields (name, rdataset) tuples for all rdatasets in the zone which have the specified *rdtype* and *covers*. If *rdtype* is ``dns.rdatatype.ANY``, the default, @@ -592,7 +583,7 @@ class Zone(dns.transaction.TransactionManager): self, rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.ANY, covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE, - ) -> Iterator[Tuple[dns.name.Name, int, dns.rdata.Rdata]]: + ) -> Iterator[tuple[dns.name.Name, int, dns.rdata.Rdata]]: """Return a generator which yields (name, ttl, rdata) tuples for all rdatas in the zone which have the specified *rdtype* and *covers*. If *rdtype* is ``dns.rdatatype.ANY``, the default, @@ -845,7 +836,7 @@ class Zone(dns.transaction.TransactionManager): def verify_digest( self, zonemd: dns.rdtypes.ANY.ZONEMD.ZONEMD | None = None ) -> None: - digests: dns.rdataset.Rdataset | List[dns.rdtypes.ANY.ZONEMD.ZONEMD] + digests: dns.rdataset.Rdataset | list[dns.rdtypes.ANY.ZONEMD.ZONEMD] if zonemd: digests = [zonemd] else: @@ -875,7 +866,7 @@ class Zone(dns.transaction.TransactionManager): def origin_information( self, - ) -> Tuple[dns.name.Name | None, bool, dns.name.Name | None]: + ) -> tuple[dns.name.Name | None, bool, dns.name.Name | None]: effective: dns.name.Name | None if self.relativize: effective = dns.name.empty @@ -1023,11 +1014,11 @@ class WritableVersion(Version): # We have to copy the zone origin as it may be None in the first # version, and we don't want to mutate the zone until we commit. self.origin = zone.origin - self.changed: Set[dns.name.Name] = set() + self.changed: set[dns.name.Name] = set() def _maybe_cow_with_name( self, name: dns.name.Name - ) -> Tuple[dns.node.Node, dns.name.Name]: + ) -> tuple[dns.node.Node, dns.name.Name]: name = self._validate_name(name) node = self.nodes.get(name) if node is None or name not in self.changed: @@ -1204,7 +1195,7 @@ class Transaction(dns.transaction.Transaction): def _origin_information( self, - ) -> Tuple[dns.name.Name | None, bool, dns.name.Name | None]: + ) -> tuple[dns.name.Name | None, bool, dns.name.Name | None]: assert self.version is not None (absolute, relativize, effective) = self.manager.origin_information() if absolute is None and self.version.origin is not None: diff --git a/dns/zonefile.py b/dns/zonefile.py index 782a935e..cb8e07cc 100644 --- a/dns/zonefile.py +++ b/dns/zonefile.py @@ -19,7 +19,8 @@ import re import sys -from typing import Any, Iterable, List, Set, Tuple, cast +from collections.abc import Iterable +from typing import Any, cast import dns.exception import dns.grange @@ -66,7 +67,7 @@ def _check_cname_and_other_data(txn, name, rdataset): # adding the rdataset is ok -SavedStateType = Tuple[ +SavedStateType = tuple[ dns.tokenizer.Tokenizer, dns.name.Name | None, # current_origin dns.name.Name | None, # last_name @@ -117,9 +118,9 @@ class Reader: self.last_name = self.current_origin self.zone_rdclass = rdclass self.txn = txn - self.saved_state: List[SavedStateType] = [] + self.saved_state: list[SavedStateType] = [] self.current_file: Any | None = None - self.allowed_directives: Set[str] + self.allowed_directives: set[str] if allow_directives is True: self.allowed_directives = {"$GENERATE", "$ORIGIN", "$TTL"} if allow_include: @@ -272,7 +273,7 @@ class Reader: self.txn.add(name, ttl, rd) - def _parse_modify(self, side: str) -> Tuple[str, str, int, int, str]: + def _parse_modify(self, side: str) -> tuple[str, str, int, int, str]: # Here we catch everything in '{' '}' in a group so we can replace it # with ''. is_generate1 = re.compile(r"^.*\$({(\+|-?)(\d+),(\d+),(.)}).*$") @@ -635,7 +636,7 @@ class RRSetsReaderManager(dns.transaction.TransactionManager): self.origin = origin self.relativize = relativize self.rdclass = rdclass - self.rrsets: List[dns.rrset.RRset] = [] + self.rrsets: list[dns.rrset.RRset] = [] def reader(self): # pragma: no cover raise NotImplementedError @@ -654,7 +655,7 @@ class RRSetsReaderManager(dns.transaction.TransactionManager): effective = self.origin return (self.origin, self.relativize, effective) - def set_rrsets(self, rrsets: List[dns.rrset.RRset]) -> None: + def set_rrsets(self, rrsets: list[dns.rrset.RRset]) -> None: self.rrsets = rrsets @@ -669,7 +670,7 @@ def read_rrsets( idna_codec: dns.name.IDNACodec | None = None, origin: dns.name.Name | str | None = dns.name.root, relativize: bool = False, -) -> List[dns.rrset.RRset]: +) -> list[dns.rrset.RRset]: """Read one or more rrsets from the specified text, possibly subject to restrictions. diff --git a/examples/reverse.py b/examples/reverse.py index a6dc1588..24a29bd8 100755 --- a/examples/reverse.py +++ b/examples/reverse.py @@ -23,7 +23,7 @@ from typing import Dict, List # pylint: disable=unused-import import dns.ipv4 import dns.zone -reverse_map = {} # type: Dict[str, List[str]] +reverse_map = {} # type: dict[str, list[str]] for filename in sys.argv[1:]: zone = dns.zone.from_file(filename, os.path.basename(filename), relativize=False) diff --git a/tests/doq.py b/tests/doq.py index e8b9bfef..8a44663b 100644 --- a/tests/doq.py +++ b/tests/doq.py @@ -95,7 +95,7 @@ class Connection: def __init__(self, listener, cid, peer, retry_cid=None): self.original_cid: bytes = cid self.listener = listener - self.cids: Set[bytes] = set() + self.cids: set[bytes] = set() self.cids.add(cid) self.listener.connections[cid] = self self.peer = peer @@ -116,7 +116,7 @@ class Connection: self.worker_scope = None self.streams = {} - def get_timer_values(self, now: float) -> Tuple[float, float]: + def get_timer_values(self, now: float) -> tuple[float, float]: expiration = self.quic_connection.get_timer() if expiration is None: expiration = now + 3600 # arbitrary "big" value diff --git a/tests/test_name.py b/tests/test_name.py index 96c03459..d0fc0e18 100644 --- a/tests/test_name.py +++ b/tests/test_name.py @@ -456,14 +456,14 @@ class NameTestCase(unittest.TestCase): def testToWire1(self): n = dns.name.from_text("FOO.bar") f = BytesIO() - compress = {} # type: Dict[dns.name.Name,int] + compress = {} # type: dict[dns.name.Name,int] n.to_wire(f, compress) self.assertEqual(f.getvalue(), b"\x03FOO\x03bar\x00") def testToWire2(self): n = dns.name.from_text("FOO.bar") f = BytesIO() - compress = {} # type: Dict[dns.name.Name,int] + compress = {} # type: dict[dns.name.Name,int] n.to_wire(f, compress) n.to_wire(f, compress) self.assertEqual(f.getvalue(), b"\x03FOO\x03bar\x00\xc0\x00") @@ -472,7 +472,7 @@ class NameTestCase(unittest.TestCase): n1 = dns.name.from_text("FOO.bar") n2 = dns.name.from_text("foo.bar") f = BytesIO() - compress = {} # type: Dict[dns.name.Name,int] + compress = {} # type: dict[dns.name.Name,int] n1.to_wire(f, compress) n2.to_wire(f, compress) self.assertEqual(f.getvalue(), b"\x03FOO\x03bar\x00\xc0\x00") @@ -481,7 +481,7 @@ class NameTestCase(unittest.TestCase): n1 = dns.name.from_text("FOO.bar") n2 = dns.name.from_text("a.foo.bar") f = BytesIO() - compress = {} # type: Dict[dns.name.Name,int] + compress = {} # type: dict[dns.name.Name,int] n1.to_wire(f, compress) n2.to_wire(f, compress) self.assertEqual(f.getvalue(), b"\x03FOO\x03bar\x00\x01\x61\xc0\x00") @@ -490,7 +490,7 @@ class NameTestCase(unittest.TestCase): n1 = dns.name.from_text("FOO.bar") n2 = dns.name.from_text("a.foo.bar") f = BytesIO() - compress = {} # type: Dict[dns.name.Name,int] + compress = {} # type: dict[dns.name.Name,int] n1.to_wire(f, compress) n2.to_wire(f, None) self.assertEqual(f.getvalue(), b"\x03FOO\x03bar\x00\x01\x61\x03foo\x03bar\x00") @@ -518,7 +518,7 @@ class NameTestCase(unittest.TestCase): def bad(): n = dns.name.from_text("FOO.bar", None) f = BytesIO() - compress = {} # type: Dict[dns.name.Name,int] + compress = {} # type: dict[dns.name.Name,int] n.to_wire(f, compress) self.assertRaises(dns.name.NeedAbsoluteNameOrOrigin, bad) @@ -526,7 +526,7 @@ class NameTestCase(unittest.TestCase): def testGiantCompressionTable(self): # Only the first 16KiB of a message can have compression pointers. f = BytesIO() - compress = {} # type: Dict[dns.name.Name,int] + compress = {} # type: dict[dns.name.Name,int] # exactly 16 bytes encoded n = dns.name.from_text("0000000000.com.") n.to_wire(f, compress)