\'Hello \' + (\'there\' if name is None else name)
Is the equivalent of
msg = \'Hello \'
if name is None:
msg += \'there\'
else:
Do not do it.
Do this instead:
% python -m this | sed 's/^R.*/======>&<======/'
Whenever I see elif
, I think dict
.
#!/usr/bin/env python
class Shrink(object):
types = {
'p': 'Pointer',
'v': 'Value',
}
def shrink_this(self):
return "'Modify %s By %s'" % (
self.types.get(self.register, 'Unknown'), self.delta)
import unittest
class TestShrink(unittest.TestCase):
def test_p(self):
s = Shrink();
s.register = 'p'
s.delta = 'delta'
self.assertEquals("'Modify Pointer By delta'", s.shrink_this())
def test_u(self):
s = Shrink();
s.register = 'u'
s.delta = 'echo'
self.assertEquals("'Modify Unknown By echo'", s.shrink_this())
def test_v(self):
s = Shrink();
s.register = 'v'
s.delta = 'foxtrot'
self.assertEquals("'Modify Value By foxtrot'", s.shrink_this())
if __name__ == '__main__':
unittest.main()
Were you to need to add r
for reference
or pp
for pointer-to-pointer
, only types
requires a change and your code remains readable.
Readability counts.