I have the Factory like this
import factory
from dataclasses import dataclass
@dataclass
class Note:
write: bool
read: bool
class NoteFactory(factory.Factory):
class Meta:
model = Note
write= False
read= False
note = NoteFactory.build(write=True)
print(note.write)
output: True
It is worked ok
I want to use variable in this case:
var_write = 'write'
note = NoteFactory.build(var_write =True)
print(note.var_write)
ouput : Note.__init__() got an unexpected keyword argument 'var_write'
It can not work How can use variable in this case or is there some workaround for this?
If I understand correctly, you want to specify the
fieldyou're setting toTruein a variable; i.e:In that case, you need to use Python's
**kwargsargument passing. A very detailed example would be:It's simpler to write it in a single line though:
However, note that this pattern will make it harder to analyse a large codebase later on: it's much harder to see where you're setting
write=True, as the definition is now spread across several lines.As a side note, you can also write
NoteFactory(...)instead ofNoteFactory.build(...): both will have the same effect.