Nik
Nik

Reputation: 201

Python calling a method from a different file defined in a class

I am trying to write a unit test. My unit test file is test_file . My main code is in a file(main_file.py) which has a class defined and several methods. All my files are in same dir, so my tree structure looks like :

├── main_file.py
├── __init__.py
├── test_file.py

In my main_file i have a class name my_class and has method send_request.

In my test file i am trying to import the method to use: from main_file import send_request

and when i run my unit test (python test_file.py) or even using nosetests it keeps throwing error: ImportError: No module named main_file

my init.py is just empty.

Upvotes: 1

Views: 66

Answers (2)

Shalini Prabhuswamy
Shalini Prabhuswamy

Reputation: 41

you have to import class to use the method

from main_file import my_class
from my_class import FUNCTION_NAME or from my_class import *

Upvotes: 0

Simeon Ikudabo
Simeon Ikudabo

Reputation: 2190

When you are importing a file, you need to import the CLASS and not just the method if it is inside of a class. So you would need to do:

from main_file import my_class

instead of importing the function within the class. Then when you call the class you can do something such as

my_class.send_request()

when you call the function in your new .py

As you know you could import all of the classes and modules from main_file by doing:

import main_file
from main_file import *

Which will get you all of the classes/functions as well, although that may not be what you're looking for.

Besides that I would make sure they're all in the same directory again, and if it still fails, I usually just save everything to my "downloads" folder. When all else fails, and then it works.

Upvotes: 1

Related Questions