Python type checking and "dns.rdata.Rdata"

31 views
Skip to first unread message

Martin T

unread,
Nov 10, 2022, 7:31:43 AM11/10/22
to dnspyth...@googlegroups.com
Hi.

Let's say, that I have a following code snippet which finds the zone
serial number:

zone = dns.zone.Zone("example.com")
dns.query.inbound_xfr("192.168.0.44", zone)
for (name, ttl, rdata) in zone.iterate_rdatas("SOA"):
serial_nr = rdata.serial

When I type check this code with mypy, then it detects the "rdata" as
"dns.rdata.Rdata" and complains that '"Rdata" has no attribute
"serial"'.

How to workaround this problem?


thanks,
Martin

Bob Halley

unread,
Nov 10, 2022, 9:12:56 AM11/10/22
to dnspython-users
dnspython's design was around "duck typing", so many things return generic types.  You've got two basic options:

1) Tell mypy what the actual type is:

    from dns.rdtypes.ANY.SOA import SOA
    from typing import cast

   
    for (name, ttl, rdata) in zone.iterate_rdatas("SOA"):
        rdata = cast(SOA, rdata)
        serial_nr = rdata.serial   # ok
        bogus = rdata.bogus        # mypy rejects; also fails at runtime

2) Use an rdata variable of type Any, either implicitly from an Any-typed API or explicitly:

    # implicit
    for rdata in zone.find_rdataset("@", "SOA"):
        serial_nr = rdata.serial   # ok as the iterator's values are Any
        bogus = rdata.bogus        # mypy does not complain; fails at runtime

    # explicit
    rdata: Any

    for (name, ttl, rdata) in zone.iterate_rdatas("SOA"):
        serial_nr = rdata.serial   # ok
        bogus = rdata.bogus        # mypy does not complain; fails at runtime

Martin T

unread,
Nov 23, 2022, 6:47:48 AM11/23/22
to dnspyth...@googlegroups.com
Hi Bob,

thanks! Casting the SOA type worked fine.


Martin
> --
> You received this message because you are subscribed to the Google Groups "dnspython-users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to dnspython-use...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/dnspython-users/54a4cab5-0808-49b4-b0f7-bbfadc65edf6n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages