I created a class EmailParser and check if a supplied string is an email or not with the help of the standard librarie's email module. If the supplied string is not an email I raise an exception.
- Is this a pythonic way to deal with inappropiate input values an assertation error?
- How do you generally check input values and report inappropiate states and values?
code:
class EmailParser(object):
def __init__(self, message):
assert isinstance(message, basestring)
parsed_message = email.message_from_string(message)
if self._is_email(parsed_message):
self.email_obj = parsed_message
else:
assert False, 'The supplied string is no email: %s' % parsed_message
def __str__(self, *args, **kwargs):
return self.email_obj.__str__()
def _is_email(self, possible_email_obj):
is_email = False
if isinstance(possible_email_obj, basestring):
is_email = False
# I struggled a lot with this part - however, I came to the conclusion
# to ask for forgiveness than for permission, see Zen of Python and
# http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python/610923#610923
try:
if '@' in possible_email_obj['To']:
is_email = True
except TypeError, e:
is_email = False
return is_email