Search code examples
pythonpython-typingmypy

Module does not explicitly export attribute [attr-defined]


In bar.py foo is imported

# bar.py
from path import foo

In my current file bar is imported and I use the get_id function of foo:

from path import bar
bar.foo.get_id()

Mypy is complaining

error: Module "bar" does not explicitly export attribute "foo"  [attr-defined]

Solution

  • Is it your own module?

    Use one of these two options that are suggested in the mypy docs; the __all__ is generally preferred

    # This will re-export it as bar and allow other modules to import it
    from foo import bar as bar
    
    # This will also re-export bar
    from foo import bar
    __all__ = ['bar']
    

    If its a 3rd party; but also valid for your on modules

    Not all modules are designed and follow these suggestions you can disable/not check for the error, but first check:

    • Is is more valid to use foo directly?

      from path import foo
      foo.get_id()
      

      I argue that the usage of module.non_child_module.function is often not justified. Also when writing your own modules it's more likely to create import-cycles when you put an unnecessary intermediate module in between.

    • If you think keeping bar.foo is more valid than using foo directly you can either add a # type: ignore[attr-defined]

    • Do not check for the error at all and use --no-implicit-reexport / implicit_reexport=False as many modules