Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 574
user238424 Avatar asked Dec 26 '09 14:12

user238424


2 Answers

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.)

like image 145
Eli Bendersky Avatar answered Oct 04 '22 07:10

Eli Bendersky


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

Who's the fool you're protecting yourself from?

You? Are you worried that you didn't remember the API you wrote?

A peer? Are you worried that someone in the next cubicle will actively make an effort to pass the wrong things through an API? You can talk to them to resolve this problem. It saves a lot of code if you provide documentation.

A total sociopath who will download your code, refuse to read the API documentation, and then call all the methods with improper arguments? What possible help can you provide to them?

The "fool-proof" coding isn't really very helpful, since all of these scenarios are more easily addressed another way.

If you're fool-proofing against yourself, perhaps that's not really sensible.

If you're fool-proofing for a co-worker or peer, you should -- perhaps -- talk to them and make sure they understand the API docs.

If you're fool-proofing against some hypothetical sociopathic programmer who's out to subvert the API, there's nothing you can do. It's Python. They have the source. Why would they go through the effort to misuse the API when they can just edit the source to break things?

like image 44
S.Lott Avatar answered Oct 04 '22 08:10

S.Lott