HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythonMinor

Raising an assertation error if string is not an email

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
erroremailraisingassertationnotstring

Problem

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

Solution

class EmailParser(object):

    def __init__(self, message):
        assert isinstance(message, basestring)


In python, we typically don't check types. Basically, we prefer duck typing. Let the user pass whatever they want.

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


As Janne mentioned, this is not a good use of an assertion.

def __str__(self, *args, **kwargs):
        return self.email_obj.__str__()


You shouldn't call __str__ methods directly. Use the str() function.

def _is_email(self, possible_email_obj):
        is_email = False

        if isinstance(possible_email_obj, basestring):
            is_email = False


This is useless, because the only possible outcome is to set is_email to False which it already is. Furthermore, you know this has to be a Message object since it was returned from message_from_string so why are you checking whether it's a string? You know its not.

# 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


In what circumstances can this possibly happen?

return is_email


Don't needlessly set boolean flags. Just return True or False directly.

Better yet, raise an exception with details on what exactly is wrong rather than returning false and raising a generic exception later.

Code Snippets

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

Context

StackExchange Code Review Q#24419, answer score: 5

Revisions (0)

No revisions yet.