Skip to content

Commit 1e3eeea

Browse files
committed
Use f-strings instead of .format or '%' which are new in Python 3.6
1 parent d4c9ec2 commit 1e3eeea

File tree

8 files changed

+22
-23
lines changed

8 files changed

+22
-23
lines changed

email_validator/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def main(dns_resolver=None):
3030
try:
3131
validate_email(email, dns_resolver=dns_resolver)
3232
except EmailNotValidError as e:
33-
print("{} {}".format(email, e))
33+
print(f"{email} {e}")
3434
else:
3535
# Validate the email address passed on the command line.
3636
email = sys.argv[1]

email_validator/deliverability.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def validate_email_deliverability(domain, domain_i18n, timeout=None, dns_resolve
4747
mtas = [(preference, exchange) for preference, exchange in mtas
4848
if exchange != ""]
4949
if len(mtas) == 0: # null MX only, if there were no MX records originally a NoAnswer exception would have occurred
50-
raise EmailUndeliverableError("The domain name %s does not accept email." % domain_i18n)
50+
raise EmailUndeliverableError(f"The domain name {domain_i18n} does not accept email.")
5151

5252
deliverability_info["mx"] = mtas
5353
deliverability_info["mx_fallback_type"] = None
@@ -73,7 +73,7 @@ def validate_email_deliverability(domain, domain_i18n, timeout=None, dns_resolve
7373
# this domain is not deliverable, although the domain
7474
# name has other records (otherwise NXDOMAIN would
7575
# have been raised).
76-
raise EmailUndeliverableError("The domain name %s does not accept email." % domain_i18n)
76+
raise EmailUndeliverableError(f"The domain name {domain_i18n} does not accept email.")
7777

7878
# Check for a SPF (RFC 7208) reject-all record ("v=spf1 -all") which indicates
7979
# no emails are sent from this domain (similar to a Null MX record
@@ -87,15 +87,15 @@ def validate_email_deliverability(domain, domain_i18n, timeout=None, dns_resolve
8787
if value.startswith(b"v=spf1 "):
8888
deliverability_info["spf"] = value.decode("ascii", errors='replace')
8989
if value == b"v=spf1 -all":
90-
raise EmailUndeliverableError("The domain name %s does not send email." % domain_i18n)
90+
raise EmailUndeliverableError(f"The domain name {domain_i18n} does not send email.")
9191
except dns.resolver.NoAnswer:
9292
# No TXT records means there is no SPF policy, so we cannot take any action.
9393
pass
9494

9595
except dns.resolver.NXDOMAIN:
9696
# The domain name does not exist --- there are no records of any sort
9797
# for the domain name.
98-
raise EmailUndeliverableError("The domain name %s does not exist." % domain_i18n)
98+
raise EmailUndeliverableError(f"The domain name {domain_i18n} does not exist.")
9999

100100
except dns.resolver.NoNameservers:
101101
# All nameservers failed to answer the query. This might be a problem

email_validator/exceptions_types.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def __self__(self):
6565
return self.normalized_email
6666

6767
def __repr__(self):
68-
return "<ValidatedEmail {}>".format(self.email)
68+
return f"<ValidatedEmail {self.email}>"
6969

7070
"""For backwards compatibility, some fields are also exposed through a dict-like interface. Note
7171
that some of the names changed when they became attributes."""

email_validator/syntax.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,9 @@
1010
def get_length_reason(addr, utf8=False, limit=EMAIL_MAX_LENGTH):
1111
"""Helper function to return an error message related to invalid length."""
1212
diff = len(addr) - limit
13-
reason = "({}{} character{} too many)"
1413
prefix = "at least " if utf8 else ""
1514
suffix = "s" if diff > 1 else ""
16-
return reason.format(prefix, diff, suffix)
15+
return f"({prefix}{diff} character{suffix} too many)"
1716

1817

1918
def safe_character_display(c):
@@ -23,9 +22,9 @@ def safe_character_display(c):
2322

2423
# Construct a hex string in case the unicode name doesn't exist.
2524
if ord(c) < 0xFFFF:
26-
h = "U+{:04x}".format(ord(c)).upper()
25+
h = f"U+{ord(c):04x}".upper()
2726
else:
28-
h = "U+{:08x}".format(ord(c)).upper()
27+
h = f"U+{ord(c):08x}".upper()
2928

3029
# Return the character name or, if it has no name, the hex string.
3130
return unicodedata.name(c, h)
@@ -55,7 +54,7 @@ def validate_email_local_part(local, allow_smtputf8=True, allow_empty_local=Fals
5554
# instead.
5655
if len(local) > LOCAL_PART_MAX_LENGTH:
5756
reason = get_length_reason(local, limit=LOCAL_PART_MAX_LENGTH)
58-
raise EmailSyntaxError("The email address is too long before the @-sign {}.".format(reason))
57+
raise EmailSyntaxError(f"The email address is too long before the @-sign {reason}.")
5958

6059
# Check the local part against the non-internationalized regular expression.
6160
# Most email addresses match this regex so it's probably fastest to check this first.
@@ -231,7 +230,7 @@ def validate_email_domain_part(domain, test_environment=False, globally_delivera
231230
try:
232231
domain = idna.uts46_remap(domain, std3_rules=False, transitional=False)
233232
except idna.IDNAError as e:
234-
raise EmailSyntaxError("The part after the @-sign contains invalid characters ({}).".format(str(e)))
233+
raise EmailSyntaxError(f"The part after the @-sign contains invalid characters ({e}).")
235234

236235
# The domain part is made up period-separated "labels." Each label must
237236
# have at least one character and cannot start or end with dashes, which
@@ -274,7 +273,7 @@ def validate_email_domain_part(domain, test_environment=False, globally_delivera
274273
# one the user supplied. Also I'm not sure if the length check applies
275274
# to the internationalized form, the IDNA ASCII form, or even both!
276275
raise EmailSyntaxError("The email address is too long after the @-sign.")
277-
raise EmailSyntaxError("The part after the @-sign contains invalid characters (%s)." % str(e))
276+
raise EmailSyntaxError(f"The part after the @-sign contains invalid characters ({e}).")
278277

279278
# Check the syntax of the string returned by idna.encode.
280279
# It should never fail.
@@ -291,14 +290,14 @@ def validate_email_domain_part(domain, test_environment=False, globally_delivera
291290
# is never reached for internationalized domains.)
292291
if len(ascii_domain) > DOMAIN_MAX_LENGTH:
293292
reason = get_length_reason(ascii_domain, limit=DOMAIN_MAX_LENGTH)
294-
raise EmailSyntaxError("The email address is too long after the @-sign {}.".format(reason))
293+
raise EmailSyntaxError(f"The email address is too long after the @-sign {reason}.")
295294

296295
# Also check the label length limit.
297296
# (RFC 1035 2.3.1)
298297
for label in ascii_domain.split("."):
299298
if len(label) > DNS_LABEL_LENGTH_LIMIT:
300299
reason = get_length_reason(label, limit=DNS_LABEL_LENGTH_LIMIT)
301-
raise EmailSyntaxError("After the @-sign, periods cannot be separated by so many characters {}.".format(reason))
300+
raise EmailSyntaxError(f"After the @-sign, periods cannot be separated by so many characters {reason}.")
302301

303302
if globally_deliverable:
304303
# All publicly deliverable addresses have domain named with at least
@@ -337,7 +336,7 @@ def validate_email_domain_part(domain, test_environment=False, globally_delivera
337336
try:
338337
domain_i18n = idna.decode(ascii_domain.encode('ascii'))
339338
except idna.IDNAError as e:
340-
raise EmailSyntaxError("The part after the @-sign is not valid IDNA ({}).".format(str(e)))
339+
raise EmailSyntaxError(f"The part after the @-sign is not valid IDNA ({e}).")
341340

342341
# Check for invalid characters after normalization. These
343342
# should never arise. See the similar checks above.

email_validator/validate_email.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,15 +101,15 @@ def validate_email(
101101
reason = get_length_reason(ret.email, utf8=True)
102102
else:
103103
reason = "(when converted to IDNA ASCII)"
104-
raise EmailSyntaxError("The email address is too long {}.".format(reason))
104+
raise EmailSyntaxError(f"The email address is too long {reason}.")
105105
if len(ret.email.encode("utf8")) > EMAIL_MAX_LENGTH:
106106
if len(ret.email) > EMAIL_MAX_LENGTH:
107107
# If there are more than 254 characters, then the UTF-8
108108
# encoding is definitely going to be too long.
109109
reason = get_length_reason(ret.email, utf8=True)
110110
else:
111111
reason = "(when encoded in bytes)"
112-
raise EmailSyntaxError("The email address is too long {}.".format(reason))
112+
raise EmailSyntaxError(f"The email address is too long {reason}.")
113113

114114
if check_deliverability and not test_environment:
115115
# Validate the email address's deliverability using DNS

tests/mocked_dns_response.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ def get(self, key):
103103
if (key[0], ANY, key[2]) in self.data and self.data[(key[0], ANY, key[2])] is None:
104104
raise dns.resolver.NXDOMAIN()
105105

106-
raise ValueError("Saved DNS data did not contain query: {}".format(key))
106+
raise ValueError(f"Saved DNS data did not contain query: {key}")
107107

108108
def put(self, key, value):
109109
# Build the DNS data by saving the live query response.

tests/test_deliverability.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,17 @@ def test_deliverability_found():
2323
def test_deliverability_fails():
2424
# No MX record.
2525
domain = 'xkxufoekjvjfjeodlfmdfjcu.com'
26-
with pytest.raises(EmailUndeliverableError, match='The domain name {} does not exist'.format(domain)):
26+
with pytest.raises(EmailUndeliverableError, match=f'The domain name {domain} does not exist'):
2727
validate_email_deliverability(domain, domain, dns_resolver=RESOLVER)
2828

2929
# Null MX record.
3030
domain = 'example.com'
31-
with pytest.raises(EmailUndeliverableError, match='The domain name {} does not accept email'.format(domain)):
31+
with pytest.raises(EmailUndeliverableError, match=f'The domain name {domain} does not accept email'):
3232
validate_email_deliverability(domain, domain, dns_resolver=RESOLVER)
3333

3434
# No MX record, A record fallback, reject-all SPF record.
3535
domain = 'nellis.af.mil'
36-
with pytest.raises(EmailUndeliverableError, match='The domain name {} does not send email'.format(domain)):
36+
with pytest.raises(EmailUndeliverableError, match=f'The domain name {domain} does not send email'):
3737
validate_email_deliverability(domain, domain, dns_resolver=RESOLVER)
3838

3939

tests/test_syntax.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,4 +559,4 @@ def test_pyisemail_tests(email_input, status):
559559
with pytest.raises(EmailSyntaxError):
560560
validate_email(email_input, test_environment=True)
561561
else:
562-
raise ValueError("status {} is not recognized".format(status))
562+
raise ValueError(f"status {status} is not recognized")

0 commit comments

Comments
 (0)