Frage

I have access to a generator that yields attribute hashes from a database via the motor Mongo adapter:

for attrs in (yield motor_generator):
  print attrs

I'm trying to create a class method that can instantiate instances of itself if given a generator, but not totally sure how to go about it. I've got:

class Model:
  @classmethod
  def instantiator(self, motor_generator):
    (self(attrs) for attrs in (yield motor_generator))

Usecase:

for instance in Model.instantiator(motor_generator):
  instance.attr = 'asdf'

But this just raised a 'yielded unknown object' error.

War es hilfreich?

Lösung

I have code snippts that can inspire you:

snippet1

class Model:
  @classmethod
  def instantiator(self, motor_generator):
    # you can not put the yield here. it will transform this function into a generator.
    return map(self, motor_generator) # map is lazy in python 3

snippet2

class Model:
  @classmethod
  def instantiator(self, motor_generator):
    attrss = motor_generator # I put this outside because i fear a syntax misunderstanding with generators
    return [self(attrs) for attrs in attrss] # with round brackets it would be evaluated on demand = in the for loop but not in this method

snippet3

for instance in Model.instantiator((yield motor_generator)):
  instance.attr = 'asdf'
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top