question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to get dict dump of Factory

See original GitHub issue

Hello,

I need to get a full dump of a Factory as a dict so that I can serialize it to json. FactoryName.attributes() works great except when there is a SubField, in which case it evaluates it and returns an instantiated version of the object as opposed to a dictionary of key: value of the SubField attributes.

I tried to hack around this by traversing the Factory myself but it turns out that I’ll have to duplicate a lot of code that already exists. Do you see an easy way to do this?

Issue Analytics

  • State:closed
  • Created 10 years ago
  • Comments:10 (5 by maintainers)

github_iconTop GitHub Comments

16reactions
aalvrzcommented, Feb 6, 2018

@rbarrois

I am trying to use the factory.build(dict, FACTORY_CLASS=MyFactory) method in my REST API tests. However, the dictionary returned by that method contains a reference to an instance of an object in SubFactory() fields:

{'isbn': '12345', 'materia': <Materia: materia_2>, 'precio': 99.99, 'titulo': 'titulo_0', 'bisac_primario': <CodigoBisac: bisac_2>, 'idioma': <Idioma: I_2 - I_2>, 'moneda': <Moneda: moneda_2>, 'volumen': 1, 'edicion': 3, 'autor': <Autor: autor_2>}

I think it would be better if this would return the ID of this object instance instead.

Is there any built-in method that does this?

5reactions
chanyou0311commented, May 31, 2020

@hectorcanto Great way!

I used that code as a reference and created a function that also outputs SubFactory as a dict.

from functools import partial
from typing import Any, Dict

from factory import Factory
from factory.base import StubObject


def generate_dict_factory(factory: Factory):
    def convert_dict_from_stub(stub: StubObject) -> Dict[str, Any]:
        stub_dict = stub.__dict__
        for key, value in stub_dict.items():
            if isinstance(value, StubObject):
                stub_dict[key] = convert_dict_from_stub(value)
        return stub_dict

    def dict_factory(factory, **kwargs):
        stub = factory.stub(**kwargs)
        stub_dict = convert_dict_from_stub(stub)
        return stub_dict

    return partial(dict_factory, factory)

# example of usage
UserDictFactory = generate_dict_factory(UserFactory)

We look forward to helping you.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to convert defaultdict of defaultdicts [of defaultdicts] to dict ...
You can recurse over the tree, replacing each defaultdict instance with a dict produced by a dict comprehension:
Read more >
Python Json | Json loads | Json dumps | Dictionary - YouTube
Python Json | Json loads | Json dumps | Dictionary ... is right one to convert those json string to dictionary for easy...
Read more >
Common recipes — Factory Boy stable documentation
Pass that dict as keyword arguments to the model's build / create function. In order to get a dict, we'll just have to...
Read more >
The Factory Method Pattern and Its Implementation in Python
Let's begin refactoring the code to achieve the desired structure that uses the Factory Method design pattern. Refactoring Code Into the Desired Interface....
Read more >
Search — Python 3.7.14 documentation
...that remembers the order entries were added defaultdict dict subclass that calls a factory function to supply missing values UserDict wrapper around ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found