Should I make python code less reliable to improve readability?

I'm trying to make my code flawless, but I noticed that it takes a lot of time to enter text, and it takes more time to read the code.

Instead:

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

I usually 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 maintaining impeccability?

  • Note 1: I added comments between <and >for clarification only.
  • Note 2: The main fool I'm trying to prevent in order to abuse my code is my future.
+5
source share
10 answers

Python :


, , . EAFP ( " , " ), LBYL ( ", " ). . :

:

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

:

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

( , , + -, 2 10 ( 32- ). , : .)

+11

" python ? , ?"

, ?

? , API, ?

? , - , API? , . , .

, , API, ? ?

"" , .

, , .

, , , , API.

- , API, . Python. . , API, , ?

+9

Python , , . self.text_values.

+3

( ).

Python LBYL ( ) . ( ) , () -.

? , . , , ? . , / ( , , LBYLing)

+3

, - . , , , , , .

+2

, assert, . , , . , . .

+2

, . , , , , ? , , , " ", " " " ".

, -, ? .

+2

, python. : - -; , (Eiffel - ) , .

, , 'checkValues', __init__. :

def __init__(self, text_values):
   self.text_values = checkValues( text_values )

def checkValues(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.'
    return( frozenset( text_values ) )

, / ; .

0

, , , , .

; , .

0

: , . AssertionError, , .

, , , :

        assert isinstance(text_value, basestring), u'All text_values should be str or unicode.'
0

All Articles