You’re looking for a Python library that implements the ACME protocol. Things are slightly more involved than retrieving a DNS record and downloading the certificate, though that is part of it.
Your best bet is probably the Python
acme library - https://pypi.org/project/acme/ . However, it has the problem of having very out of date documentation.
I think maybe if you want an easy to use approach, you can just use Certbot in combination with a manual auth hook.
certbot certonly --manual -d example.org -d www.example.org \
--preferred-challenges dns \
--manual-auth-hook "/path/to/dns.py deploy" \
--manual-cleanup-hook "/path/to/dns.py cleanup"
Certbot will run your Python script with environment variables containing the DNS record and you can use that to deploy the TXT record. At the end, Certbot will automatically download your certificate.
This is probably a much simpler path unless you want to implement an entire ACME client, which is quite involved.