Passing arguments to a custom exception

I recently learned how to create custom exceptions in Python and inject them into a class. I am trying to add an extra argument to my exception for clarity and cannot force the formatting correctly.

Here is what I am trying:

class NonIntError(Exception):
    pass

class intlist(List):

    def __init__(self, lst = []):

        for item in lst:
            #throws error if list contains something other that int
            if type(item) != int:
                raise NonIntError(item, 'not an int') 

            else:
                self.append(item)

Expected results

il = intlist([1,2,3,'apple'])

>>> NonIntError: apple not an int

Error Results

il = intlist([1,2,3,'apple'])

>>> NonIntError: ('apple', 'not an int')

Repeating my question, I would like to know how to make my exception look like the expected results.

+4
source share
2 answers

item 'not an int'. , * args :

>>> raise NonIntError('hi', 1, [1,2,3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.NonIntError: ('hi', 1, [1, 2, 3])

, , :

>>> item = 'apple'
>>> raise NonIntError(item + ' not an int')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.NonIntError: apple not an int
+3

timgeb, :

, int, :

class intlist(object):

    def __init__(self, lst = []):
        not_int_list = filter(lambda x: not isinstance(x, int), lst)
        if not_int_list:
            if len(not_int_list) > 1:
                items = ', '.join(not_int_list)
                raise NonIntError(items + ' are not int type')
            item = not_int_list.pop()
            raise NonIntError(item + ' is not int type')

il = intlist([1,2,3,'apple']), :

>>> NonIntError: apple is not int type

il = intlist([1,2,3,'apple','banana']), :

>>> NonIntError: apple, banana are not int type

, , int, .


:

not_int_list = filter(lambda x: not isinstance(x, int), lst)

filter isinstance .

if len(not_int_list) > 1:
    items = ', '.join(not_int_list)
    raise NonIntError(items + ' are not int type')
item = not_int_list.pop()
raise NonIntError(item + ' is not int type')

, .

NonIntError(items + ' are not int type')

timgeb. .

+1

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


All Articles