3
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$
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.

\$\endgroup\$
4
\$\begingroup\$

Assertions are meant to help find bugs in the program. See Python Wiki: Using assertion effectively. Quote:

Assertions should not be used to test for failure cases that can occur because of bad user input or operating system/environment failures, such as a file not being found. Instead, you should raise an exception, or print an error message, or whatever is appropriate. One important reason why assertions should only be used for self-tests of the program is that assertions can be disabled at compile time.

If Python is started with the -O option, then assertions will be stripped out and not evaluated. So if code uses assertions heavily, but is performance-critical, then there is a system for turning them off in release builds. (But don't do this unless it's really necessary. It's been scientifically proven that some bugs only show up when a customer uses the machine and we want assertions to help there too.)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.