rthalley / dnspython

a powerful DNS toolkit for python
http://www.dnspython.org
Other
2.46k stars 518 forks source link

How to access exchange and preferenc of Rdata object #1141

Closed ghost closed 1 month ago

ghost commented 1 month ago

Describe the bug: Up to v2.6.1 one could use rdata.exchange and rdata.preference to access the exchange and preference of the Rdata objects when resolving for rdtype MX. With v2.7.0 the Rdata objects have no attributes exchange or preference.

(I opened this as an issue instead of a question/discussion, because it affects the official examples which many probably use as a starting point when working with dnspython.)

To Reproduce: See examples/mx.py

Resulting errors:

mx.py:7: error: "Rdata" has no attribute "exchange"  [attr-defined]
mx.py:7: error: "Rdata" has no attribute "preference"  [attr-defined]

Context:

rthalley commented 1 month ago

This will still work if you run it. The problem is that I didn't anticipate the effect of an iterator type change I merged into 2.7 on this kind of checking. Dnspython was designed with duck typing long ago, and the type of the iterator's value needs to be Any to avoid this. Alternatively, you can have exact typing with this less pretty bit of code:

#!/usr/bin/env python3

from typing import cast

import dns.resolver
from dns.rdtypes.ANY.MX import MX

answers = dns.resolver.resolve("nominum.com", "MX")
for rdata in answers:
    mxrdata = cast(MX, rdata)
    print("Host", mxrdata.exchange, "has preference", mxrdata.preference)
rthalley commented 1 month ago

Fixed.