Cemre Mengü
Cemre Mengü

Reputation: 18754

Importing specific classes from a file located in a python package

I have a python package main and other_python_files which are like:

main/
    __init__.py
    lib.py
    other_python_files/
        __init__.py
        test.py

Let lib.py contain a class called MyClass. When I do from main import lib.py and use MyClass inside test.py I get the error that MyClass is not defined.

I tried doing from main import MyClass inside the init file in the main directory but I still get the same error. What should I do to achieve importing a specific class from the lib.py file ?

Upvotes: 0

Views: 113

Answers (1)

Blender
Blender

Reputation: 298206

You either have to import that class out of lib:

from main.lib import MyClass

Or use lib.MyClass in place of MyClass.

You can also import MyClass inside of the __init__.py file that's in main, which lets you import it the way you originally tried:

__all__ = ['MyClass']

from lib import MyClass

You can read about __all__ here: Can someone explain __all__ in Python?

Upvotes: 2

Related Questions