From 9689f6e083726416b02b8821e04b27b2100460d7 Mon Sep 17 00:00:00 2001 From: Maxim Vladimirsky Date: Thu, 24 Jul 2014 12:15:37 +0400 Subject: [PATCH] Fix doc strings --- flanker/addresslib/address.py | 108 +++++++++++++++++--------------- flanker/addresslib/corrector.py | 8 +-- flanker/addresslib/parser.py | 108 +++++++++++++++++++++----------- flanker/addresslib/tokenizer.py | 24 +++---- flanker/addresslib/validate.py | 32 +++++----- 5 files changed, 159 insertions(+), 121 deletions(-) diff --git a/flanker/addresslib/address.py b/flanker/addresslib/address.py index 92aac2c..7c57120 100644 --- a/flanker/addresslib/address.py +++ b/flanker/addresslib/address.py @@ -1,6 +1,6 @@ # coding:utf-8 -''' +""" Public interface for flanker address (email or url) parsing and validation capabilities. @@ -32,7 +32,7 @@ When valid addresses are returned, they are returned as an instance of either EmailAddress or UrlAddress in flanker.addresslib.address. See the parser.py module for implementation details of the parser. -''' +""" import time import flanker.addresslib.parser @@ -47,7 +47,7 @@ from urlparse import urlparse @metrics_wrapper() def parse(address, addr_spec_only=False, metrics=False): - ''' + """ Given an string, returns a scalar object representing a single full mailbox (display name and addr-spec), addr-spec, or a url. @@ -69,7 +69,7 @@ def parse(address, addr_spec_only=False, metrics=False): >>> print address.parse('foo') None - ''' + """ mtimes = {'parsing': 0} parser = flanker.addresslib.parser._AddressParser(False) @@ -95,7 +95,7 @@ def parse(address, addr_spec_only=False, metrics=False): @metrics_wrapper() def parse_list(address_list, strict=False, as_tuple=False, metrics=False): - ''' + """ Given an string or list of email addresses and/or urls seperated by a delimiter (comma (,) or semi-colon (;)), returns an AddressList object (an iterable list representing parsed email addresses and urls). @@ -123,7 +123,7 @@ def parse_list(address_list, strict=False, as_tuple=False, metrics=False): >>> address.parse_list('A , D , http://localhost') [A , D , http://localhost] - ''' + """ mtimes = {'parsing': 0} parser = flanker.addresslib.parser._AddressParser(strict) @@ -151,7 +151,7 @@ def parse_list(address_list, strict=False, as_tuple=False, metrics=False): @metrics_wrapper() def validate_address(addr_spec, metrics=False): - ''' + """ Given an addr-spec, runs the pre-parser, the parser, DNS MX checks, MX existence checks, and if available, ESP specific grammar for the local part. @@ -168,7 +168,7 @@ def validate_address(addr_spec, metrics=False): >>> address.validate_address('user.1234@gmail.com') user.1234@gmail.com - ''' + """ mtimes = {'parsing': 0, 'mx_lookup': 0, 'dns_lookup': 0, 'mx_conn':0 , 'custom_grammar':0} @@ -211,7 +211,7 @@ def validate_address(addr_spec, metrics=False): @metrics_wrapper() def validate_list(addr_list, as_tuple=False, metrics=False): - ''' + """ Validates an address list, and returns a tuple of parsed and unparsed portions. @@ -228,11 +228,10 @@ def validate_list(addr_list, as_tuple=False, metrics=False): >>> address.validate_address_list('a@b, c@d, e@example.com', as_tuple=True) ([a@mailgun.com, c@mailgun.com], ['e@example.com']) - ''' + """ mtimes = {'parsing': 0, 'mx_lookup': 0, 'dns_lookup': 0, 'mx_conn':0 , 'custom_grammar':0} - if addr_list is None: return None, mtimes @@ -293,32 +292,33 @@ def is_email(string): class Address(object): - ''' + """ Base class that represents an address (email or URL). Use it to create concrete instances of different addresses: - ''' + """ @property def supports_routing(self): - "Indicates that by default this address cannot be routed" + """ + Indicates that by default this address cannot be routed. + """ return False - class Type(object): - ''' + """ Enumerates the types of addresses we support: >>> parse('foo@example.com').addr_type 'email' >>> parse('http://example.com').addr_type 'url' - ''' + """ Email = 'email' Url = 'url' class EmailAddress(Address): - ''' + """ Represents a fully parsed email address with built-in support for MIME encoding. Note, do not use EmailAddress class directly, use the parse() or parse_list() functions to return a scalar or iterable list respectively. @@ -341,7 +341,7 @@ class EmailAddress(Address): And full email spec is 100% ASCII, encoded for MIME: >>> addr.full_spec() 'Bob Silva ' - ''' + """ __slots__ = ['display_name', 'mailbox', 'hostname', 'address'] @@ -365,22 +365,24 @@ class EmailAddress(Address): self.addr_type = self.Type.Email def __repr__(self): - ''' + """ >>> repr(EmailAddress("John Smith", "john@smith.com")) 'John Smith ' - ''' + """ return self.full_spec() def __str__(self): - ''' + """ >>> str(EmailAddress("boo@host.com")) 'boo@host.com' - ''' + """ return self.address @property def supports_routing(self): - "Email addresses can be routed" + """ + Email addresses can be routed. + """ return True @property @@ -394,7 +396,7 @@ class EmailAddress(Address): self._display_name = value def full_spec(self): - ''' + """ Returns a full spec of an email address. Always in ASCII, RFC-2822 compliant, safe to be included into MIME: @@ -402,13 +404,15 @@ class EmailAddress(Address): 'Ev K ' >>> EmailAddress("Жека", "ev@example.com").full_spec() '=?utf-8?b?0JbQtdC60LA=?= ' - ''' + """ if self._display_name: return '{0} <{1}>'.format(self._display_name, self.address) return u'{0}'.format(self.address) def to_unicode(self): - "Converts to unicode" + """ + Converts to unicode. + """ if self.display_name: return u'{0} <{1}>'.format(self.display_name, self.address) return u'{0}'.format(self.address) @@ -417,7 +421,9 @@ class EmailAddress(Address): return True def __eq__(self, other): - "Allows comparison of two addresses" + """ + Allows comparison of two addresses. + """ if other: if isinstance(other, basestring): other = parse(other) @@ -427,7 +433,7 @@ class EmailAddress(Address): return False def __hash__(self): - ''' + """ Hashing allows using Address objects as keys in collections and compare them in sets @@ -440,13 +446,12 @@ class EmailAddress(Address): >>> s.add(b) >>> len(s) 1 - ''' + """ return hash(self.address.lower()) - class UrlAddress(Address): - ''' + """ Represents a parsed URL: >>> url = UrlAddress("http://user@host.com:8080?q=a") >>> url.hostname @@ -460,7 +465,7 @@ class UrlAddress(Address): Note: do not create UrlAddress class directly by passing raw "internet data", use the parse() and parse_list() functions instead. - ''' + """ __slots__ = ['address', 'parse_result'] @@ -496,9 +501,6 @@ class UrlAddress(Address): def to_unicode(self): return self.address - def __str__(self): - return self.address - def __repr__(self): return self.address @@ -514,7 +516,7 @@ class UrlAddress(Address): class AddressList(object): - ''' + """ Keeps the list of addresses. Each address is an EmailAddress or URLAddress objectAddress-derived object. @@ -526,7 +528,7 @@ class AddressList(object): False >>> "bob@host.COM" in al True - ''' + """ def __init__(self, container=None): if container is None: @@ -550,19 +552,20 @@ class AddressList(object): return len(self.container) def __eq__(self, other): - "When comparing ourselves to other lists we must ignore order" + """ + When comparing ourselves to other lists we must ignore order. + """ if isinstance(other, list): other = parse_list(other) return set(self.container) == set(other.container) - def __str__(self): - return ''.join(['[', self.full_spec(), ']']) - def __repr__(self): return ''.join(['[', self.full_spec(), ']']) def __add__(self, other): - "Adding two AddressLists together yields another AddressList" + """ + Adding two AddressLists together yields another AddressList. + """ if isinstance(other, list): result = self.container + parse_list(other).container else: @@ -570,13 +573,13 @@ class AddressList(object): return AddressList(result) def full_spec(self, delimiter=", "): - ''' + """ Returns a full string which looks pretty much what the original was like >>> adl = AddressList("Foo , Bar ") >>> adl.full_spec(delimiter='; ') 'Foo ' - ''' + """ return delimiter.join(addr.full_spec() for addr in self.container) def to_unicode(self, delimiter=u", "): @@ -587,12 +590,12 @@ class AddressList(object): @property def addresses(self): - ''' + """ Returns a list of just addresses, i.e. no names: >>> adl = AddressList("Foo , Bar ") >>> adl.addresses ['foo@host.com', 'bar@host.com'] - ''' + """ return [addr.address for addr in self.container] def __str__(self): @@ -600,13 +603,14 @@ class AddressList(object): @property def hostnames(self): - "Returns a set of hostnames used in addresses in this list" + """ + Returns a set of hostnames used in addresses in this list. + """ return set([addr.hostname for addr in self.container]) @property def addr_types(self): - "Returns a set of address types used in addresses in this list" + """ + Returns a set of address types used in addresses in this list. + """ return set([addr.addr_type for addr in self.container]) - - - diff --git a/flanker/addresslib/corrector.py b/flanker/addresslib/corrector.py index 49fdd92..9032dad 100644 --- a/flanker/addresslib/corrector.py +++ b/flanker/addresslib/corrector.py @@ -1,5 +1,5 @@ # coding:utf-8 -''' +""" Spelling corrector library, used to correct common typos in domains like gmal.com instead of gmail.com. @@ -12,16 +12,16 @@ a domain, suggests an alternative or returns the original domain if no suggestion exists. [1] http://xlinux.nist.gov/dads/HTML/ratcliffObershelp.html -''' +""" import difflib def suggest(word, cutoff=0.77): - ''' + """ Given a domain and a cutoff heuristic, suggest an alternative or return the original domain if no suggestion exists. - ''' + """ if word in LOOKUP_TABLE: return LOOKUP_TABLE[word] diff --git a/flanker/addresslib/parser.py b/flanker/addresslib/parser.py index 509e7a4..70794b6 100644 --- a/flanker/addresslib/parser.py +++ b/flanker/addresslib/parser.py @@ -1,6 +1,6 @@ # coding:utf-8 -''' +""" _AddressParser is an implementation of a recursive descent parser for email addresses and urls. While _AddressParser can be used directly it is not recommended, use the the parse() and parse_list() methods which are provided @@ -54,7 +54,7 @@ Additional limitations on email addresses: is 64 + 1 + 253 = 318 characters. Allow 194 characters for a display name and the (very generous) limit becomes 512 characters. Allow 1024 mailboxes and the total limit on a mailbox-list is 524288 characters. -''' +""" import re import flanker.addresslib.address @@ -86,24 +86,24 @@ from flanker.utils import to_utf8 class _AddressParser(object): - ''' + """ Do not use _AddressParser directly because it heavily relies on other private classes and methods and it's interface is not guarenteed, it will change in the future and possibly break your application. Instead use the parse() and parse_list() functions in the address.py module which will always return a scalar or iterable respectively. - ''' + """ def __init__(self, strict=False): self.stream = None self.strict = strict def address_list(self, stream): - ''' + """ Extract a mailbox and/or url list from a stream of input, operates in strict and relaxed modes. - ''' + """ # sanity check if not stream: raise ParserException('No input provided to parser.') @@ -123,10 +123,10 @@ class _AddressParser(object): return self._address_list_relaxed() def address(self, stream): - ''' + """ Extract a single address or url from a stream of input, always operates in strict mode. - ''' + """ # sanity check if not stream: raise ParserException('No input provided to parser.') @@ -152,10 +152,10 @@ class _AddressParser(object): return None def address_spec(self, stream): - ''' + """ Extract a single address spec from a stream of input, always operates in strict mode. - ''' + """ # sanity check if stream is None: raise ParserException('No input provided to parser.') @@ -182,7 +182,9 @@ class _AddressParser(object): def _mailbox_post_processing_checks(self, address): - "Additional post processing checks to ensure mailbox is valid." + """ + Additional post processing checks to ensure mailbox is valid. + """ parts = address.split('@') # check if local part is less than 1024 octets, the actual @@ -211,7 +213,9 @@ class _AddressParser(object): return True def _address_list_relaxed(self): - "Grammar: address-list-relaxed -> address { delimiter address }" + """ + Grammar: address-list-relaxed -> address { delimiter address } + """ #addrs = [] addrs = flanker.addresslib.address.AddressList() unparsable = [] @@ -282,7 +286,9 @@ class _AddressParser(object): return addrs, unparsable def _address_list_strict(self): - "Grammar: address-list-strict -> address { delimiter address }" + """ + Grammar: address-list-strict -> address { delimiter address } + """ #addrs = [] addrs = flanker.addresslib.address.AddressList() @@ -308,7 +314,9 @@ class _AddressParser(object): return addrs def _address(self): - "Grammar: address -> name-addr-rfc | name-addr-lax | addr-spec | url" + """ + Grammar: address -> name-addr-rfc | name-addr-lax | addr-spec | url + """ start_pos = self.stream.position addr = self._name_addr_rfc() or self._name_addr_lax() or \ @@ -324,14 +332,18 @@ class _AddressParser(object): return addr def _url(self): - "Grammar: url -> url" + """ + Grammar: url -> url + """ earl = self.stream.get_token(URL) if earl is None: return None return flanker.addresslib.address.UrlAddress(to_utf8(earl)) def _name_addr_rfc(self): - "Grammar: name-addr-rfc -> [ display-name-rfc ] angle-addr-rfc" + """ + Grammar: name-addr-rfc -> [ display-name-rfc ] angle-addr-rfc + """ start_pos = self.stream.position # optional displayname @@ -348,7 +360,9 @@ class _AddressParser(object): return flanker.addresslib.address.EmailAddress(None, aaddr) def _display_name_rfc(self): - "Grammar: display-name-rfc -> [ whitespace ] word { whitespace word }" + """ + Grammar: display-name-rfc -> [ whitespace ] word { whitespace word } + """ wrds = [] # optional whitespace @@ -376,9 +390,9 @@ class _AddressParser(object): return cleanup_display_name(''.join(wrds)) def _angle_addr_rfc(self): - ''' - Grammar: angle-addr-rfc -> [ whitespace ] < addr-spec > [ whitespace ]" - ''' + """ + Grammar: angle-addr-rfc -> [ whitespace ] < addr-spec > [ whitespace ] + """ start_pos = self.stream.position # optional whitespace @@ -411,7 +425,9 @@ class _AddressParser(object): return aspec def _name_addr_lax(self): - "Grammar: name-addr-lax -> [ display-name-lax ] angle-addr-lax" + """ + Grammar: name-addr-lax -> [ display-name-lax ] angle-addr-lax + """ start_pos = self.stream.position # optional displayname @@ -428,10 +444,10 @@ class _AddressParser(object): return flanker.addresslib.address.EmailAddress(None, aaddr) def _display_name_lax(self): - ''' + """ Grammar: display-name-lax -> - [ whitespace ] word { whitespace word } whitespace" - ''' + [ whitespace ] word { whitespace word } whitespace + """ start_pos = self.stream.position wrds = [] @@ -482,7 +498,9 @@ class _AddressParser(object): return cleanup_display_name(''.join(wrds)) def _angle_addr_lax(self): - "Grammar: angle-addr-lax -> addr-spec [ whitespace ]" + """ + Grammar: angle-addr-lax -> addr-spec [ whitespace ] + """ start_pos = self.stream.position # addr-spec @@ -498,9 +516,9 @@ class _AddressParser(object): return aspec def _addr_spec(self, as_string=False): - ''' + """ Grammar: addr-spec -> [ whitespace ] local-part @ domain [ whitespace ] - ''' + """ start_pos = self.stream.position # optional whitespace @@ -533,16 +551,22 @@ class _AddressParser(object): return flanker.addresslib.address.EmailAddress(None, aspec) def _local_part(self): - "Grammar: local-part -> dot-atom | quoted-string" + """ + Grammar: local-part -> dot-atom | quoted-string + """ return self.stream.get_token(DOT_ATOM) or \ self.stream.get_token(QSTRING) def _domain(self): - "Grammar: domain -> dot-atom" + """ + Grammar: domain -> dot-atom + """ return self.stream.get_token(DOT_ATOM) def _word(self): - "Grammar: word -> word-ascii | word-unicode" + """ + Grammar: word -> word-ascii | word-unicode + """ start_pos = self.stream.position # ascii word @@ -557,7 +581,9 @@ class _AddressParser(object): return self._word_unicode() def _word_ascii(self): - "Grammar: word-ascii -> atom | qstring" + """ + Grammar: word-ascii -> atom | qstring + """ wrd = self.stream.get_token(RELAX_ATOM) or self.stream.get_token(QSTRING) if wrd and not contains_control_chars(wrd): return wrd @@ -565,7 +591,9 @@ class _AddressParser(object): return None def _word_unicode(self): - "Grammar: word-unicode -> unicode-atom | unicode-qstring" + """ + Grammar: word-unicode -> unicode-atom | unicode-qstring + """ start_pos = self.stream.position # unicode atom @@ -584,15 +612,21 @@ class _AddressParser(object): def _whitespace(self): - "Grammar: whitespace -> whitespace-ascii | whitespace-unicode" + """ + Grammar: whitespace -> whitespace-ascii | whitespace-unicode + """ return self._whitespace_ascii() or self._whitespace_unicode() def _whitespace_ascii(self): - "Grammar: whitespace-ascii -> whitespace-ascii" + """ + Grammar: whitespace-ascii -> whitespace-ascii + """ return self.stream.get_token(WHITESPACE) def _whitespace_unicode(self): - "Grammar: whitespace-unicode -> whitespace-unicode" + """ + Grammar: whitespace-unicode -> whitespace-unicode + """ uwhite = self.stream.get_token(UNI_WHITE) if uwhite and not is_pure_ascii(uwhite): return uwhite @@ -600,9 +634,9 @@ class _AddressParser(object): class ParserException(Exception): - ''' + """ Exception raised when the parser encounters some parsing exception. - ''' + """ def __init__(self, reason='Unknown parser error.'): self.reason = reason diff --git a/flanker/addresslib/tokenizer.py b/flanker/addresslib/tokenizer.py index 628092d..605d22d 100644 --- a/flanker/addresslib/tokenizer.py +++ b/flanker/addresslib/tokenizer.py @@ -1,11 +1,11 @@ # coding:utf-8 -''' +""" TokenStream represents a stream of tokens that a parser will consume. TokenStream can be used to consume tokens, peek ahead, and synchonize to a delimiter token. The tokens that the token stream operates on are either compiled regular expressions or strings. -''' +""" import re @@ -73,23 +73,23 @@ URL = re.compile(r''' ''', re.MULTILINE | re.VERBOSE | re.UNICODE) class TokenStream(object): - ''' + """ Represents the stream of tokens that the parser will consume. The token stream can be used to consume tokens, peek ahead, and synchonize to a delimiter token. When the strem reaches its end, the position is placed at one plus the position of the last token. - ''' + """ def __init__(self, stream): self.position = 0 self.stream = stream def get_token(self, token, ngroup=None): - ''' + """ Get the next token from the stream and advance the stream. Token can be either a compiled regex or a string. - ''' + """ # match single character if isinstance(token, basestring) and len(token) == 1: if self.peek() == token: @@ -112,19 +112,19 @@ class TokenStream(object): return None def end_of_stream(self): - ''' + """ Check if the end of the stream has been reached, if it has, returns True, otherwise false. - ''' + """ if self.position >= len(self.stream): return True return False def synchronize(self): - ''' + """ Advances the stream to synchronizes to the delimiter token. Used primarily in relaxed mode parsing. - ''' + """ start_pos = self.position end_pos = len(self.stream) @@ -142,10 +142,10 @@ class TokenStream(object): return skip def peek(self, token=None): - ''' + """ Peek at the stream to see what the next token is or peek for a specific token. - ''' + """ # peek at whats next in the stream if token is None: if self.position < len(self.stream): diff --git a/flanker/addresslib/validate.py b/flanker/addresslib/validate.py index 57c89a8..a85e3cc 100644 --- a/flanker/addresslib/validate.py +++ b/flanker/addresslib/validate.py @@ -1,6 +1,6 @@ # coding:utf-8 -''' +""" Validation module that that supports alternate spelling suggestions for domains, MX record lookup and query, as well as custom local-part grammar for large ESPs. @@ -31,7 +31,7 @@ Public Functions in flanker.addresslib.validate module: * connect_to_mail_exchanger(mx_hosts) Attempts to connect to a given mail exchanger to see if it exists. -''' +""" import re import redis @@ -44,7 +44,7 @@ from flanker.utils import metrics_wrapper def suggest_alternate(addr_spec): - ''' + """ Given an addr-spec, suggests a alternate addr-spec if common spelling mistakes are detected in the domain portion. @@ -56,7 +56,7 @@ def suggest_alternate(addr_spec): None >>> validate.suggest_alternate('john@gmail..com') 'john@gmail.com' - ''' + """ # sanity check if addr_spec is None: return None @@ -78,9 +78,9 @@ def suggest_alternate(addr_spec): def preparse_address(addr_spec): - ''' + """ Preparses email addresses. Used to handle odd behavior by ESPs. - ''' + """ # sanity check, ensure we have both local-part and domain parts = addr_spec.split('@') if len(parts) < 2: @@ -95,7 +95,7 @@ def preparse_address(addr_spec): def plugin_for_esp(mail_exchanger): - ''' + """ Checks if custom grammar exists for a particular mail exchanger. If a grammar is found, the plugin to validate an address for that particular email service provider is returned, otherwise None is returned. @@ -103,7 +103,7 @@ def plugin_for_esp(mail_exchanger): If you are adding the grammar for a email service provider, add the module to the flanker.addresslib.plugins directory then update the flanker.addresslib package to add it to the known list of custom grammars. - ''' + """ for grammar in flanker.addresslib.CUSTOM_GRAMMAR_LIST: if grammar[0].match(mail_exchanger): return grammar[1] @@ -113,11 +113,11 @@ def plugin_for_esp(mail_exchanger): @metrics_wrapper() def mail_exchanger_lookup(domain, metrics=False): - ''' + """ Looks up the mail exchanger for a domain. If MX records exist they will be returned, if not it will attempt to fallback to A records, if neither exist None will be returned. - ''' + """ mtimes = {'mx_lookup': 0, 'dns_lookup': 0, 'mx_conn': 0} mx_cache = flanker.addresslib.mx_cache @@ -155,13 +155,13 @@ def mail_exchanger_lookup(domain, metrics=False): def lookup_exchanger_in_cache(domain): - ''' + """ Uses a cache to store the results of the mail exchanger lookup to speed up lookup times. The default is redis, but this can be overidden by your own cache as long as it conforms to the same interface as that of a dict. See the implimentation of the redis cache in the flanker.addresslib.driver package for more details if you wish to implement your own cache. - ''' + """ mx_cache = flanker.addresslib.mx_cache lookup = mx_cache[domain] @@ -175,14 +175,14 @@ def lookup_exchanger_in_cache(domain): def lookup_domain(domain): - ''' + """ The dnspython package is used for dns lookups. The dnspython package uses the dns server specified by your operating system. Just like the cache, this can be overridden by your own dns lookup method of choice as long as it conforms to the same interface as that of a dict. See the the implimentation of the dnspython lookup in the flanker.addresslib.driver package for more details. - ''' + """ dns_lookup = flanker.addresslib.dns_lookup @@ -195,10 +195,10 @@ def lookup_domain(domain): def connect_to_mail_exchanger(mx_hosts): - ''' + """ Given a list of MX hosts, attempts to connect to at least one on port 25. Returns the mail exchanger it was able to connect to or None. - ''' + """ for host in mx_hosts: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -- 2.43.0