dennismonsewicz
dennismonsewicz

Reputation: 25542

Shortening Python Lambda

The code below takes a value and returns it if the value is of basestring. If the the value is not of basestring, then convert it to a string, but if the value is None, then return an empty string.

Is there a more Pythonic way of doing this?

lambda value: value if isinstance(value, basestring) else str(value) if value is not None else ""

Upvotes: 1

Views: 165

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117951

I wouldn't even bother checking if it is a string, just convert it regardless (This will work in Python 3.x but not 2.x).

lambda value: str(value) if value is not None else ""

The reason is that if it is already a str, then calling str() will basically do nothing.

>>> s = 'test'
>>> id(s)
35584672
>>> id(str(s))
35584672
>>> j = str(s)
>>> id(j)
35584672

Notice they all have the same id? This means no new object was created.

Upvotes: 6

Related Questions