TypeError: <lambda>() missing 1 required positional argument:

Efie picture Efie · Dec 5, 2017 · Viewed 20.1k times · Source

I'm trying to populate my Django project with some random data using factory_boy and faker. However, when I try to create an instance of my UserFactory object I'm getting the error TypeError: () missing 1 required positional argument: 'a'.

It seems to have something to do with the fake_date and date_joined attributes and their lambda functions. A couple of the tutorials I've found have laid out using lambda functions in this way for the Factory objects but it isn't working for me.

import datetime
import factory
import faker
from dataStoreApp.models import Category, Goal, Transaction
from django.contrib.auth.models import User

fake = faker.Faker()


class CategoryFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = Category

    name = factory.Iterator(['Category1', 'Category2',
                             'Category3', 'Category4',
                             'Category5', ], cycle=False)


class UserFactory(factory.django.DjangoModelFactory):
    FACTORY_HIDDEN_ARGS = ('fake_date', )

    class Meta:
        model = User

    fake_date = factory.LazyAttribute(
    lambda a: datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
    date_joined = factory.LazyFunction(lambda a: a.fake_date)
    first_name = factory.LazyAttribute(lambda b: fake.first_name())
    last_name = factory.LazyAttribute(lambda c: fake.last_name())
    email = factory.LazyAttribute(lambda e: 'test' + '@test_email.com')



class GoalFactory(factory.DjangoModelFactory):
    class Meta:
        model = Goal


class TransactionFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Transaction

When running in the python console I get the following errors:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\Python36\lib\site-packages\factory\base.py", line 568, in create
    return cls._generate(enums.CREATE_STRATEGY, kwargs)
  File "C:\Program Files\Python36\lib\site-packages\factory\base.py", line 505, in _generate
    return step.build()
  File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 272, in build
    step.resolve(pre)
  File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 221, in resolve
    self.attributes[field_name] = getattr(self.stub, field_name)
  File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 363, in __getattr__
    extra=declaration.context,
  File "C:\Program Files\Python36\lib\site-packages\factory\declarations.py", line 59, in evaluate
    return self.function()
TypeError: <lambda>() missing 1 required positional argument: 'a'

Answer

furas picture furas · Dec 5, 2017

You create function with argument a in code

lambda a: ....

but it seems program expects function without arguments

lambda: ...