Uz_IT
Uz_IT

Reputation: 27

Import one class in another within same folder

I have a folder named 'container' which have two classes:

  1. VisitorPage.py
  2. TestMethods.py
  3. __init__.py

I want to import 'VisitorPage' in TestMethods class so I can use its methods.

I have tried following, but not succeeded yet.

from .containers import VisitorPage

Error:

from .containers import VisitorPage
ModuleNotFoundError: No module named 'tests.containers.containers'

Second scenario:

from containers import VisitorPage

Error

from containers import VisitorPage
ModuleNotFoundError: No module named 'containers'

Scenario 3:

import containers.VisitorPage

Error:

import containers.VisitorPage
ModuleNotFoundError: No module named 'containers'

Can someone please let me know the correct way to do it. Thanks

Upvotes: 0

Views: 67

Answers (1)

lightalchemist
lightalchemist

Reputation: 10211

The error is telling you the problem. Both VisitorPage and TestMethods are in the folder containers. Using . refers to the current module. Using .containers means you are searching for a module containers within containers.

My guess is your project structure is

containers/
|- VisitorPage.py
|- TestMethods.py

If that is the case, then inside TestMethods.py, just

import VisitorPage

Otherwise, you need to put containers in a directory so that your directory structure is

project/    
    |-containers/
         |- VisitorPage.py
         |- TestMethods.py

where project is the root directory.

So inside TestMethods.py, you import VisitorPage using relative import

from . import VisitorPage

or if you want to use absolute import

from containers import VisitorPage

Upvotes: 1

Related Questions