How use variable in factory boy build

65 Views Asked by At

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?

1

There are 1 best solutions below

1
Xelnor On

If I understand correctly, you want to specify the field you're setting to True in a variable; i.e:

>>> var_field = "write"
>>> NoteFactory.build(...)  # The "..." is the syntax we're interested in
Note(read=False, write=True)
>>> var_field = "read"
>>> NoteFactory.build(...)  # The "..." is the syntax we're interested in
Note(read=True, write=False)

In that case, you need to use Python's **kwargs argument passing. A very detailed example would be:

>>> var_field = "write"
>>> kwargs = {var_field: True}
>>> kwargs
{"write": True}
>>> NoteFactory.build(**kwargs)
Note(read=False, write=True)

It's simpler to write it in a single line though:

>>> var_field = "write"
>>> NoteFactory(**{var_field: True})
Note(read=False, write=True)

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 of NoteFactory.build(...): both will have the same effect.