Search code examples
pythonmypydnspython

How to configure mypy to ignore a stub file for a specific module?


I installed a "dnspython" package with "pip install dnspython" under Ubuntu 22.10 and made a following short script:

#!/usr/bin/env python3

import dns.zone
import dns.query

zone = dns.zone.Zone("example.net")
dns.query.inbound_xfr("10.0.0.1", zone)

for (name, ttl, rdata) in zone.iterate_rdatas("SOA"):
    serial_nr = rdata.serial

When I check this code snippet with mypy(version 0.990), then it reports an error: Module has no attribute "inbound_xfr" [attr-defined] for line number 7.

According to mypy documentation, if a Python file and a stub file are both present in the same directory on the search path, then only the stub file is used. In case of "dnspython", the stub file query.pyi is present in the dns package and the stub file indeed has no attribute "inbound_xfr". When I rename or remove the stub file, then the query.py Python file is used instead of the stub file and mypy no longer complains about missing attribute.

I guess this is a "dnspython" bug? Is there a way to tell to mypy that for query module, the stub file should be ignored?


Solution

  • I would recommend ignoring only the specific wrong line, not the whole module.

    dns.query.inbound_xfr("10.0.0.1", zone)  # type: ignore[attr-defined]
    

    This will suppress attr-defined error message that is generated on that line. If you're going to take this approach, I'd also recommend running mypy with the --warn-unused-ignores flag, which will report any redundant and unused # type: ignore statements (for example, after updating the library).