Created
October 9, 2016 17:48
-
-
Save asfaltboy/79a02a2b9871501af5f00c95daaeb6e7 to your computer and use it in GitHub Desktop.
EmailType: a custom argparse type to validate email addresses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A custom type for argparse, to facilitate validation of email addresses. | |
Inspired by this SO question: http://stackoverflow.com/questions/14665234/argparse-choices-structure-of-allowed-values | |
and this gist: https://gist.github.com/gurunars/449edbccd0de1449b71524c89d61e1c5 | |
""" | |
import re | |
import argparse | |
class EmailType(object): | |
""" | |
Supports checking email agains different patterns. The current available patterns is: | |
RFC5322 (http://www.ietf.org/rfc/rfc5322.txt) | |
""" | |
patterns = { | |
'RFC5322': re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"), | |
} | |
def __init__(self, pattern): | |
if pattern not in self.patterns: | |
raise KeyError('{} is not a supported email pattern, choose from:' | |
' {}'.format(pattern, ','.join(self.patterns))) | |
self._rules = pattern | |
self._pattern = self.patterns[pattern] | |
def __call__(self, value): | |
if not self._pattern.match(value): | |
raise argparse.ArgumentTypeError( | |
"'{}' is not a valid email - does not match {} rules".format(value, self._rules)) | |
return value | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('email', type=EmailType('RFC5322')) | |
args = parser.parse_args() | |
print(args.email) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for creating this! Here’s a simpler variation for anyone wanting something more succinct: