23
'Hello ' + ('there' if name is None else name)

Is the equivalent of

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

What is the equivalent of this:

msg = 'Hello '
if name is None:
    msg += 'there'
elif name == 'Mr Anderson'
    msg += 'Neo'
else:
    msg += name

EDIT: for reference here is the code I wanted to shrink

srepr = '\'Modify '
if self.register == 'p':
    srepr += 'Pointer'
elif self.register == 'v':
    srepr += 'Value'
else
    srepr += 'Unknown'
srepr += ' By ' + str(self.delta) + '\''
1
  • 4
    srepr+={'p': 'Pointer', 'v': 'Value'}.get(self.register,'Unknown') Commented Jan 6, 2011 at 13:42

7 Answers 7

38
msg = "Hi " + ("there" if not name else ("Neo" if name == "Anderson" else name))

I think that's pretty unreadable, though.

Sign up to request clarification or add additional context in comments.

3 Comments

You have unnecessary parentheses which make this less readable. See my answer for a clearer solution.
@glenn. I added those parentheses in order to make it more readable, but I guess that's subjective. In any case I think we all agree nobody should ever write nothing similar.
Nice answer - but if I ever see this in a production codebase, I'm going to have a long day. :P
8

Use a dictionary to perform a mapping:

srepr = "'Modify " + {"p": "Pointer", "v": "value"}.get(self.register, "Unknown")

(by the way, instead of '\'...' you can use "'... for a bit more clarity.

Comments

8
msg = 'Hello ' + (
    'there' if name is None else
    'Neo' if name == 'Mr Anderson' else
    name
)

This is a reiteration of several other answers, but with nicer formatting. I consider this most readable, and this is the approach I would use.

Comments

3
'Hello ' + \
('there' if name is None else \
    'Neo' if name == 'Mr Anderson' else \
    name)

I recommend against this; if your conditions become this complex, stick it in a function.

1 Comment

This is the approach I would use, but as it's written here, the formatting is unnecessarily noisy. See my answer for a version without backslashes and with consistent indentation.
2

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.

3 Comments

Ouch. Why the down-vote? "The Zen of Python" is important reading for any Python programmer (along with PEP008). The sed command emphasises the point.
The question says Python 3.x. Use return "'Modify {} By {}'".format( self.types.get(self.register, 'Unknown'), self.delta)
And a second down-vote: "If you see misinformation, vote it down. Add comments indicating what, specifically, is wrong. Provide better answers of your own. Best of all — edit and improve the existing questions and answers!" --Be Honest, SO FAQ <stackoverflow.com/faq>
0

You could also do this:

msg= 'Hello ' + {name is None: 'there', name == 'Mr Anderson': 'Neo'}.get(True, name)

So either of name is None or name == 'Mr Anderson' is True, or none of them is True, then name will be used.

Comments

-2

Firstly, run 'pip install pyswitch'

Then:

import pyswitch

mySwitch = pyswitch.Switch()

@mySwitch.case(None):
def gotNone(value):
    return 'Hello there'

@mySwitch.case('Mr. Anderson')
def gotMrAnderson(value):
    return 'Hello Neo'

@mySwitch.default
def gotDefault(value):
    return 'Hello %s' % value

msg = mySwitch.switch(None)  # Returns 'Hello there'
msg = mySwitch.switch('Mr. Anderson')  # Returns 'Hello Neo'
msg = mySwitch.switch('OoglyMoogly')  # Returns 'Hello OoglyMoogly'

2 Comments

As the length of your 'elif' chain grows, this solution's appeal grows. It's basically a something like a C language switch statement for Python. See pypi.python.org/…
if it comes to that, one could just use a dictionary with cases as keys, and a possibly lambda function as values. way much simpler that a pyswitch even in large statments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.