konradhalas / dacite

Simple creation of data classes from dictionaries.
MIT License
1.76k stars 106 forks source link

Add Generic Hook Types #83

Open channelcat opened 4 years ago

channelcat commented 4 years ago

Added in the ability to hook all of a major type, and added tests/docs. From the Readme:

To target all types use Any. Targeting collections without their sub-types will target all collections of those types, such as List and Dict.

@dataclass
class ShoppingCart:
    store: str
    item_ids: List[int]

data = {
    'store': '7-Eleven',
    'item_ids': [1, 2, 3],
}

def print_value(value):
    print(value)
    return value

def print_collection(collection):
    for item in collection:
        print(item)
    return collection

result = from_dict(
    data_class=ShoppingCart, 
    data=data, 
    config=Config(
        type_hooks={
            Any: print_value, 
            List: print_collection
        }
    )
)

prints

7-Eleven
[1, 2, 3]
1
2
3
konradhalas commented 4 years ago

Hi @channelcat - thank you for PR :)

It looks that it makes sense - let me think about it for a moment. I'll try to review your code during my next "open source sprint" ;)