Python import error "module 'factory' has no attribute 'fuzzy'"
Asked Answered
W

1

8

I'm a new to factory_boy module. In my code, I import factory and then used this import to access the fuzzy attribute with factory.fuzzy then it throws error module 'factory' has no attribute 'fuzzy'.

I solved this problem by again importing like this
import factory from factory import fuzzy

by doing so there were no errors.

What is the reason for this!

Wiggle answered 29/3, 2020 at 12:35 Comment(1)
are you sure about that. Please try it again.Goods
B
6

Why this happens?

When you import a Python module (your import factory), you can then access directly what is declared in that module (e.g factory.Factory): all symbols declared in the module are automatically exported.

However, if a nested module is not imported in its parent, you have to import it directly.

Here, factory.Factory is available, because factory/__init__.py contains:

from .base import Factory

=> When you type factory.Factory, Python looks up the symbol named Factory in factory/__init__.py, which is (per the above line) a reference to the Factory class defined in factory/base.py.

Since there is no line with from . import fuzzy in factory/__init__.py, Python cannot load it this way.

But why don't you add this line?

Other modules in the factory_boy package have dependencies on third-party packages; for instance, factory.django imports Django. If factory/__init__.py contained the from . import django line (required to have factory.django available from import factory), every program that runs import factory would require to have Django installed.

In order to allow users of the package to decide what they depend on, the choice was made to not add those direct imports at the package top-level when possible — this allows for future versions to add external dependencies without breaking existing code.

Blackout answered 30/3, 2020 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.