genomoncology / related

Nested Object Models in Python with dictionary, YAML, and JSON transformation support
MIT License
198 stars 15 forks source link

Help regarding custom yaml #44

Open Fuhrmann opened 4 years ago

Fuhrmann commented 4 years ago

Hi! I'm trying to use your library with a custom yaml file I have:

devices:
    left-keyboard:  000123456789
    right-keyboard: 000987654321

How could I represent this yaml in a class? I've tried this:

@related.immutable
class Device(object):
    name = related.StringField()

@related.immutable
class Settings(object):
    devices = related.MappingField(Device, "name")

But it gives me an error: TypeError: 000123456789 is not an instance of <class '__main__.Device'>

I've tried using SetField, SequenceField and others in this case but to no success.

M0r13n commented 2 years ago

@Fuhrmann

You could use the following model:

import related

@related.immutable
class Settings(object):
    devices = related.MappingField(str, "name")

Explanation:

Your YAML file is syntactically equivalent to the following Dictionary:

{
    'devices': {
        'left-keyboard': '000123456789',
        'right-keyboard': '000987654321',
    }
}

So

{
        'left-keyboard': '000123456789',
        'right-keyboard': '000987654321',
 }

is passed to the MappingField. So 'left-keyboard' will be used as the name and 000123456789 to whatever class is passed to the cls parameter of MappingField - in our example this is str.