Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using list comprehensions and exceptions?

Okay lets say I have a list, and I want to check if that list exists within another list. I can do that doing this:

all(value in some_map for value in required_values)

Which works fine, but lets say I want to the raise an exception when a required value is missing, with the value that it is missing. How can I do that using list comprehension?

I'm more or less curious, all signs seem to point to no.

EDIT Argh I meant this:

for value in required_values:
 if value not in some_map:
  raise somecustomException(value)

Looking at those I cant see how I can find the value where the error occurred

like image 848
UberJumper Avatar asked Dec 05 '22 06:12

UberJumper


2 Answers

lets say i want to the raise an exception when a required value is missing, with the value that it is missing. How can i do that using list comprehension?

List comprehensions are a syntactically concise way to create a list based on some existing list—they're not a general-purpose way of writing any for-loop in a single line. In this example, you're not actually creating a list, so it doesn't make any sense to use a list comprehension.

like image 163
Miles Avatar answered Dec 08 '22 16:12

Miles


You can't use raise in a list comprehension. You can check for yourself by looking at the grammar in the Python Language Reference.

You can however, invoke a function which raises an exception for you.

like image 45
Laurence Gonsalves Avatar answered Dec 08 '22 14:12

Laurence Gonsalves