Python inline elif possible?

前端 未结 7 2257
耶瑟儿~
耶瑟儿~ 2021-02-07 11:16
\'Hello \' + (\'there\' if name is None else name)

Is the equivalent of

msg = \'Hello \'
if name is None:
    msg += \'there\'
else:
          


        
相关标签:
7条回答
  • 2021-02-07 12:15

    Do not do it.

    Do this instead:

    % python -m this | sed 's/^R.*/======>&<======/'
    

    EDIT: For reference, here is how I would refactor this code...

    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.

    0 讨论(0)
提交回复
热议问题