Home > Enterprise >  Mapping keys to objects
Mapping keys to objects

Time:07-20

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())

CodePudding user response:

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]
  • Related