Search code examples
pythoncoding-stylereadability

Should I make my python code less fool-proof to improve readability?


I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code.

Instead of:

class TextServer(object):
    def __init__(self, text_values):
        self.text_values = text_values
        # <more code>
    # <more methods>

I tend to write this:

class TextServer(object):
    def __init__(self, text_values):
        for text_value in text_values:
            assert isinstance(text_value, basestring), u'All text_values should be str or unicode.'
            assert 2 <= len(text_value), u'All text_values should be at least two characters long.'
        self.__text_values = frozenset(text_values) # <They shouldn't change.>
        # <more code>
    @property
    def text_values(self):
        # <'text_values' shouldn't be replaced.>
        return self.__text_values
    # <more methods>

Is my python coding style too paranoid? Or is there a way to improve readability while keeping it fool-proof?

  • Note 1: I've added the comments between < and > just for clarification.
  • Note 2: The main fool I try to prevent to abuse my code is my future self.

Solution

  • Here's some good advice on Python idioms from this page:


    Catch errors rather than avoiding them to avoid cluttering your code with special cases. This idiom is called EAFP ('easier to ask forgiveness than permission'), as opposed to LBYL ('look before you leap'). This often makes the code more readable. For example:

    Worse:

    #check whether int conversion will raise an error
    if not isinstance(s, str) or not s.isdigit:
        return None
    elif len(s) > 10:    #too many digits for int conversion
        return None
    else:
        return int(str)
    

    Better:

    try:
        return int(str)
    except (TypeError, ValueError, OverflowError): #int conversion failed
        return None
    

    (Note that in this case, the second version is much better, since it correctly handles leading + and -, and also values between 2 and 10 billion (for 32-bit machines). Don't clutter your code by anticipating all the possible failures: just try it and use appropriate exception handling.)