2

I have some python library with Record class. Record class accepts data using only kwargs. I populate Records like this and it works ok:


class Animal(Record):
    name = String(required=True)


animal = Animal(**{'name': 'joe'})

The library also supports nesting Records like this:

class Fur(Record):
    color = String(required=True)


class Animal(Record):
    fur = Fur(required=True)

However when I try to populate with:

animal = Animal(**{'fur': {'color': 'red'}})

it fails because the subrecord do not receive color=red but receives {'color': 'red'} instead.

So I would need a kind of "recursive **" ?

JOhn
  • 313
  • 2
  • 9

1 Answers1

2

What about simply doing:

animal = Animal(fur = Fur(color = 'red'))

A little more about kwargs: What is the purpose and use of **kwargs?

Though, I don't think you can you can do it with a raw dictionary like this. If you take a look at the __init__ (here) of the Record class, you'll see that the kwargs just override the default value of the field and is set with setattr. So if you do animal = Animal(**{'fur': {'color': 'red'}}), you simply affect the dictionary {'color': 'red'} to the field fur.

The only way I can think of would be to override the Record class, for example something like this (not tested):

class SRecord(Record):
    def __setattr__(self, key, value):
        if type(self._fields.get(key, None)) is SRecord:
            value = SRecord(value)
        super(SRecord, self).__setattr__(key, value)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
olinox14
  • 6,177
  • 2
  • 22
  • 39