0

Let's say I have a 'line_item' object with values x, y, and z. If I used the following code:

columns_to_write = [
    "x",
    "y",
    "z",
]
params = (line_item.get(col) for col in columns_to_write)

And let's say there's a specific issue which sometimes occurs in 'z', where I want to cast it to a string if it's not a string. What would be the syntax for that be? I'm imagining something like...

params = (if col == "z" then str(line_item.get(col)) else line_item.get(col) for col in columns_to_write)
  • What does it matter? if you cast a string to a string then it stays a string so just cast always – Sayse Apr 02 '21 at 20:47
  • Does this answer your question? [if/else in a list comprehension](https://stackoverflow.com/questions/4260280/if-else-in-a-list-comprehension) – mkrieger1 Apr 02 '21 at 20:48

1 Answers1

0

You probably want:

params = (str(line_item.get(col)) if col == "z" else line_item.get(col) for col in columns_to_write)

However, you can also check if the thing returned is the correct type (a str in your case):

params = (line_item.get(col) if type(col) == str else str(line_item.get(col)) for col in columns_to_write)

Further, you can just always have it cast to a str, if that is the required type. Casting a str to a str is okay.

params = map(lambda x: str(line_item.get(x)), columns_to_write)
Adam Jamil
  • 21
  • 3