205

Before you mark it as duplicate please read my problem:

I am trying to import a class from a file from a subdirectory

> main.py > --->folder/ > ----->file.py 

and in file.py i have a class imlpemented ( Klasa) What have I tried:

putting in main.py:

from folder import file from file import Klasa 

I am getting the error:

from file import Klasa

ImportError: No module named 'file'

When I try to use just:

from folder import file 

I get this error:

tmp = Klasa()

NameError: name 'Klasa' is not defined

I have put an empty __init__.py in the subfolder and it still does not work, and I have put in the __init__.py : from file import Klasa and still doesnt work.

If main and file are in the same folder this work:

from file import Klasa

but i want them to be in separate files.

Can someone tell me what i am doing wrong?

1
  • 1
    import sys sys.path.append(".") from file import Klasa Commented Dec 30, 2020 at 10:33

1 Answer 1

360

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa 

Or, with from folder import file:

from folder import file k = file.Klasa() 

Or again:

import folder.file as myModule k = myModule.Klasa() 
Sign up to request clarification or add additional context in comments.

2 Comments

It works for me once I include an empty __init__.py file in the target directory containing class that is to be imported.
Simply "import Useful_Classes" (in file called "Useful_Classes.py") and then "from Useful_Classes import Hypothesis_Set" works. I added the magical/highly-nonintuitive/WTF !?!?! file "_ _ init _ _ .py" (no spaces in file name, spaces introduced to avoid unintentional bolding by HTML) to the directory. I also had to restart the kernel. There were many wrong turns on the route to this solution. This answer was one of the wrong turns. Python 3.10 in May 2022.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.