Mapping keys to objects

Question:

What would be the best way to map keys to classes? Names are familiar, but not the same. I know that data_to_object implementation with ifs is bad, but it’s just to get the point.

errors = {
    'BadRequest': {
        'title': "Some title",
        'description': "Some description"
    },
    'NotFoundError': {
        'title': "Some title2",
        'description': "Some description2"
    }
}
    

class HttpException(Exception):
    title: str 
    description: str 


class HttpNotFound(HttpException):
    ...

 
class HTTPBadRequest(HttpException):
    ...
    

def data_to_object(errors):
    data = list()
    for key, value in errors.items():
        if key == 'NotFoundError':
            data.append(HttpNotFound(title=value['title'], value=['description']))
        if key == 'BadRequest':
            data.append(HTTPBadRequest(title=value['title'], value=['description']))
    return data

list_of_objects = data_to_object(errors)

Expected result:

list_of_objects = [HttpNotFound(), HTTPBadRequest())
Asked By: Chaban33

||

Answers:

You would just create a dictionary that maps a key to a class:

map = {
    'BadRequest': HTTPBadRequest,
    'NotFoundError': HttpNotFound
}

def data_to_object(errors):
    return [map[key](title=value['title'],description=value['description'])
           for key, value in errors.items() if key in map]
Answered By: trincot
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.