Using lists and exceptions?

Well, let's say I have a list, and I want to check if this list exists in another list. I can do it:

all(value in some_map for value in required_values)

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

I'm more or less curious, all the signs seem to indicate an absence.

EDIT Argh I meant this:

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

Looking at those that I can’t understand, how can I find the value in which the error occurred

+4
source share
7 answers

, , , , . , ?

- - - for -loop . , .

+14

, . , "" , :

required_values = set('abc') # store this as a set from the beginning
values = set('ab')
missing = required_values - values
if missing:
    raise SomeException('The values %r are not in %r' % 
                        (missing, required_values))
+2

. , Python.

, .

+2

() error_on_false:

def error_on_false(value)
    if value:
        return value
    else:
        raise Exception('Wrong value: %r' % value)

if all(error_on_false(value in some_map) for value in required_values):
    continue_code()
    do_something('...')

. set.

0

. - , . - .

def iter_my_class(my_class_list):
    for c in my_class_list:
        if not isinstance(c, MyClass):
            raise ValueError('Expected MyClass')
        yield c

classes = [c for c in iter_my_class(my_class_list)]

. , .

0

, , - , .

(_ for _ in ()) , throw, , .

all((_ for _ in ()).throw(somecustomException(value)) for value in required_values if value not in some_map)

, , , . , :

map_values=[some_map[value] if value in some_map else (_ for _ in ()).throw(somecustomException(value)) for value in required_values]

, , . - , KeyError .

try:
    found_values=[some_map[value] for value in required_values]
except KeyError as e:
    raise somecustomException(e.args[0])
0

, (, nosklo) , - :

def has_required(some_map, value):
  if not value in some_map:
    raise RequiredException('Missing required value: %s' % value)

all(has_required(some_map, value) for value in required_values)
-2

Source: https://habr.com/ru/post/1709613/


All Articles