Project 5 · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
from enum import Enum

class Err(Enum):
    BAD = (1, ValueError, 'Bad value.')

print(Err.BAD.value)
try:
    Err(1)
except ValueError:
    print('no member with value 1')
2. Inside an enumeration's __new__, what does assigning member._value_ = ex_code achieve?
3. Why is the method called throw rather than raise?
4. What does this print?
class Demo:
    default = 'Default message.'

    def text_or(self, message=None):
        return message or self.default

    def text_is(self, message=None):
        return self.default if message is None else message

d = Demo()
print(repr(d.text_or('')), repr(d.text_is('')))
5. Two members are accidentally given the same error code. What happens without @unique?
from enum import Enum

class Err(Enum):
    NotAList = 201
    NotATuple = 201

print(Err.NotATuple.name, len(Err))
6. AppException.NotAList.throw() is called inside try: ... except ValueError: .... Which statement is correct?

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Goal 1: one member per error

Complete the AppException enumeration so that each member stores three things from its tuple:

- its code, which must be the member's value (so AppException(201) returns AppException.NotAList), also available as a read-only code property, - its exception class, as the attribute exception, - its default message, as the attribute message.

Lookup by name (AppException['Timeout']) must keep working, and there must be exactly four members.

Hints (3)
  1. Define __new__(cls, ex_code, ex_class, ex_message): each member's tuple is unpacked into these arguments.
  2. Create the member with object.__new__(cls), set member._value_ = ex_code, attach the other two attributes and return it.
  3. A @property named code can simply return self.value.
Show a solution
from enum import Enum

class GenericException(Exception):
    pass

class Timeout(Exception):
    pass

class AppException(Enum):
    Generic = (100, GenericException, 'Application exception.')
    Timeout = (101, Timeout, 'Timeout connecting to resource.')
    NotAnInteger = (200, ValueError, 'Value must be an integer.')
    NotAList = (201, ValueError, 'Value must be a list.')

    def __new__(cls, ex_code, ex_class, ex_message):
        member = object.__new__(cls)
        member._value_ = ex_code
        member.exception = ex_class
        member.message = ex_message
        return member

    @property
    def code(self):
        return self.value

Exercise 2: Goal 2: raise with one call

Add a throw(message=None) method to AppException. It must raise the member's exception class with the message '<code> - <message>', using the member's default message when no message is given.

For example, AppException.Timeout.throw() raises Timeout('101 - Timeout connecting to resource.'), and AppException.Timeout.throw('Database timeout.') raises Timeout('101 - Database timeout.').

Use the default only when message is None: an explicitly passed empty string is kept as is.

Hints (3)
  1. self.exception is a class: calling it, self.exception('text'), creates an exception instance you can raise.
  2. Build the text with an f-string: f'{self.code} - {message}'.
  3. message or self.message would also replace ''. Test message is None instead.
Show a solution
from enum import Enum

class GenericException(Exception):
    pass

class Timeout(Exception):
    pass

class AppException(Enum):
    Generic = (100, GenericException, 'Application exception.')
    Timeout = (101, Timeout, 'Timeout connecting to resource.')
    NotAnInteger = (200, ValueError, 'Value must be an integer.')
    NotAList = (201, ValueError, 'Value must be a list.')

    def __new__(cls, ex_code, ex_class, ex_message):
        member = object.__new__(cls)
        member._value_ = ex_code
        member.exception = ex_class
        member.message = ex_message
        return member

    @property
    def code(self):
        return self.value

    def throw(self, message=None):
        if message is None:
            message = self.message
        raise self.exception(f'{self.code} - {message}')

Exercise 3: Goal 3: list the errors

Add two class methods to AppException:

- catalog() returns a list of (name, code, message) tuples for every member, in definition order. - raising(exc_class) returns a list of the members whose exception class is exc_class or a subclass of it, in definition order.

Adding these methods must not add members to the enumeration.

Hints (2)
  1. Inside a class method, cls is the enumeration, and iterating it yields the members in definition order.
  2. issubclass(ex.exception, exc_class) is True for the class itself and for its subclasses.
Show a solution
from enum import Enum

class GenericException(Exception):
    pass

class Timeout(Exception):
    pass

class AppException(Enum):
    Generic = (100, GenericException, 'Application exception.')
    Timeout = (101, Timeout, 'Timeout connecting to resource.')
    NotAnInteger = (200, ValueError, 'Value must be an integer.')
    NotAList = (201, ValueError, 'Value must be a list.')

    def __new__(cls, ex_code, ex_class, ex_message):
        member = object.__new__(cls)
        member._value_ = ex_code
        member.exception = ex_class
        member.message = ex_message
        return member

    @property
    def code(self):
        return self.value

    @classmethod
    def catalog(cls):
        return [(ex.name, ex.code, ex.message) for ex in cls]

    @classmethod
    def raising(cls, exc_class):
        return [ex for ex in cls if issubclass(ex.exception, exc_class)]