792

I have a directory that stores all the .py files.

bin/
   main.py
   user.py # where class User resides
   dir.py # where class Dir resides

I want to use classes from user.py and dir.py in main.py.
How can I import these Python classes into main.py?
Furthermore, how can I import class User if user.py is in a sub directory?

bin/
    dir.py
    main.py
    usr/
        user.py
kenorb
  • 118,428
  • 63
  • 588
  • 624
Bin Chen
  • 54,865
  • 51
  • 136
  • 180
  • See also answers in [Python: import a file from a subdirectory](http://stackoverflow.com/questions/1260792/python-import-a-file-from-a-subdirectory). – Trilarion Mar 19 '14 at 09:55
  • [I answered similar question here](http://stackoverflow.com/a/39152647/1911412) – kchoi Aug 25 '16 at 23:33

15 Answers15

1094

Python 2

Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory".

Then just do...

from user import User
from dir import Dir

The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path.

bin/
    main.py
    classes/
        user.py
        dir.py

So if the directory was named "classes", then you'd do this:

from classes.user import User
from classes.dir import Dir

Python 3

Same as previous, but prefix the module name with a . if not using a subdirectory:

from .user import User
from .dir import Dir
Amber
  • 446,318
  • 77
  • 595
  • 531
  • Is it required that the `__init__.py` is empty. I would like to import all submodules in package `__init__.py` i.e add lines: `from Module1 impotr *` for all modules (files) I have in directory. Is it possible? – running.t Apr 15 '13 at 12:07
  • 22
    If `__init__.py` is *not* empty, then whatever is in `__init__.py` is what will be available when you import the package (and things not imported into `__init__.py` won't be available at all). – Amber Apr 15 '13 at 15:31
  • 29
    Why is an `__init__.py` file needed at all? If I put all three files in the same directory and run `main.py`, it's able to `import` from the other two modules fine without it. What am I missing? – martineau Sep 18 '13 at 13:55
  • 37
    Because that's how Python identifies directories from which you're allowed to import. The directory of the script you're running is an exception - you're always allowed to import from it. – Amber Sep 20 '13 at 05:47
  • 2
    Sorry Amber, I put an empty `__init__.py` file in the 2 subdirectories I have (gui/ and logic/), but I am still having import problems `ImportError: No module named 'player'` , this `player.py` is inside `logic/`, and there's the `__init__.py`, as I told you. What could be the problem? – nbro Nov 30 '14 at 12:26
  • 24
    @nbro & Amber: FWIW, I think something subtle has changed with regards to `__init__.py` and being able to import other modules in the same directory. Specifically `import`s of other modules in the same directory as the `__init__.py` file itself which worked in Python 2.7.8, failed in Python 3.4.1. To fix it I had to prefix each of them with the subdirectory's name and a dot (i.e. `import module` had to be changed to `import subdirectory.module`). Fortunately it still worked in Python 2.7.8 after doing this. – martineau Dec 01 '14 at 12:24
  • 3
    @martineau Exactly, and it's a more object-oriented way of importing modules. – nbro Dec 01 '14 at 12:49
  • 2
    @nbo: Since the other modules are in the same directory as the `__init__.py` and that it used to work without the prefix, I consider it a bug...perhaps an unintended consequence of something else that was changed between Python 2.x to 3.x with regards to module and package importation. – martineau Dec 01 '14 at 13:00
  • 11
    I can confirm this solution is no longer functional. You might wish to correct, amend or outright delete it. – Luís de Sousa Apr 08 '16 at 07:42
  • 2
    I likewise don't see this working in Python 3 anymore. I think this is because my module only contain functions, no classes. – Frikster Sep 26 '16 at 04:20
  • 3
    Ah, yes I solved it. Use: from . import fileloader if your module has no classes – Frikster Sep 26 '16 at 04:37
  • What do you have to do it you have stuff in your __init__.py file? I try importing from the same folder like here, and It can't find it. If I import those two files on the __init__.py it works... but doesn't if you try to import from any other – darkgaze Oct 04 '16 at 14:43
  • 1
    @darkgaze if an `__init__.py` file is non-empty, than the module will only contain what is defined in the `__init__.py` file. So your `__init__.py` needs to import from the local directory anything you want other files to be able to import from the module. (An empty `__init__.py` means to just reference the rest of the directory implicitly.) – Amber Oct 05 '16 at 00:42
  • @Amber Ok. But HOW do I do it. doing imports? How should those imports be? import childName? or import thisName.childName?. And how do you import the submodules from each of them? import childName too? – darkgaze Oct 05 '16 at 07:16
  • 1
    By the way, I found: https://www.python.org/dev/peps/pep-0328/#id8 PEP 328 talks specifically about the relative imports. – darkgaze Oct 05 '16 at 10:45
  • The first few lines of this answer were bad and didn't work at all. On the point working answer here: https://stackoverflow.com/a/41276151/129202 – Jonny May 29 '18 at 05:25
  • With Python 3.8 the import will be `import path.to.file.containing.Class` and add `__init__.py` in the directory containing the final .py file. However what is the solution if the path starts in an ancestor of the directory containing the file with the `import`. We cannot specify the path like `../../end.of.the.path.file.containg.Class`. This can happen if there are multiple directories in the project directory, of which one contains the Class to import. What is the solution, if any. – mins Mar 03 '21 at 17:16
  • python 3.9.2 no "." required. eg "from dog import Dog" where class Dog resides in dog.py – RichieHH Mar 24 '21 at 20:42
  • None of the solutions worked for me. – Bersan Mar 31 '21 at 14:06
158

I just learned (thanks to martineau's comment) that, in order to import classes from files within the same directory, you would now write in Python 3:

from .user import User
from .dir import Dir
Community
  • 1
  • 1
ecp
  • 1,931
  • 1
  • 9
  • 7
  • 24
    if i try this no i get the following error `ValueError: Attempted relative import in non-package` but error goes away when i change to `from user import User ` – Korpel Feb 23 '16 at 08:18
  • I use from .fileloader import Fileloader and get ImportError: cannot import name 'Fileloader' – Frikster Sep 26 '16 at 04:22
  • 3
    @Korpel: Following the discussions in http://stackoverflow.com/questions/11536764/how-to-fix-attempted-relative-import-in-non-package-even-with-init-py i come to realize that wether the above given import works or not depends on: [1] how your script is called (as package or not) [2] where the actual work path is when you execute it [3] how the path variable of your run environment is populated – ecp Oct 19 '16 at 15:41
  • @Korpel: I noticed that the . before the module name is required only when a __init__.py file is present, if not the . can/must be omitted. – MUG4N Jun 04 '20 at 07:24
  • 22
    Why is it so difficult to find a clear answer for this question? All I want to do is create a class in a seperate file and then import that class into a different file which is in the same directory. If I use a relative import like this answer I also get the VlaueError – Jiren Jul 31 '20 at 19:46
48

In your main.py:

from user import Class

where Class is the name of the class you want to import.

If you want to call a method of Class, you can call it using:

Class.method

Note that there should be an empty __init__.py file in the same directory.

ThatMSG
  • 1,206
  • 1
  • 13
  • 25
user225312
  • 108,033
  • 64
  • 161
  • 179
  • 3
    What do you do if the module you're trying to import has no classes? Just raw functions? In python 2 all I had to do was 'import module'. Doesn't work in python 3, neither does 'import .module' – Frikster Sep 26 '16 at 04:23
  • 3
    This works in python3 after deleted the `__init__.py`. – engineforce May 08 '19 at 04:37
35

In python3, __init__.py is no longer necessary. If the current directory of the console is the directory where the python script is located, everything works fine with

import user

However, this won't work if called from a different directory, which does not contain user.py.
In that case, use

from . import user

This works even if you want to import the whole file instead of just a class from there.

lucidbrot
  • 3,789
  • 2
  • 27
  • 54
  • 3
    I'm using pylint in vs code, and was having trouble with a same-directory import always being flagged as an error (`import user` was underlined in red); changed to the relative import (`from . import user`) and the linter no longer flagged it. – rbatt Jan 01 '20 at 00:39
  • how to do you fin the current directory – xiaodai Sep 25 '20 at 05:36
  • @xiaodai not sure what you mean. Does my second snippet not work for you? To answer your question itself, probably with `os.getcwd()` but that shouldn't be necessary – lucidbrot Sep 25 '20 at 05:38
  • " from dog import Dog" works for me 3.9.2 – RichieHH Mar 24 '21 at 20:44
16

You can import the module and have access through its name if you don't want to mix functions and classes with yours

import util # imports util.py

util.clean()
util.setup(4)

or you can import the functions and classes to your code

from util import clean, setup
clean()
setup(4)

you can use wildchar * to import everything in that module to your code

from util import *
clean()
setup(4)
joe
  • 379
  • 3
  • 11
A.Zaben
  • 647
  • 6
  • 8
13

If user.py and dir.py are not including classes then

from .user import User
from .dir import Dir

is not working. You should then import as

from . import user
from . import dir
Andreas Foteas
  • 192
  • 1
  • 9
  • could you clarify on what you mean by 'not including classes'? – AlphaCR Jun 30 '20 at 10:52
  • I mean that in the `file.py` there are defined only variables and functions `def` and no classes as described [here](https://docs.python.org/3/tutorial/classes.html) – Andreas Foteas Jul 01 '20 at 11:53
11

To make it more simple to understand:

Step 1: lets go to one directory, where all will be included

$ cd /var/tmp

Step 2: now lets make a class1.py file which has a class name Class1 with some code

$ cat > class1.py <<\EOF
class Class1:
    OKBLUE = '\033[94m'
    ENDC = '\033[0m'
    OK = OKBLUE + "[Class1 OK]: " + ENDC
EOF

Step 3: now lets make a class2.py file which has a class name Class2 with some code

$ cat > class2.py <<\EOF
class Class2:
    OKBLUE = '\033[94m'
    ENDC = '\033[0m'
    OK = OKBLUE + "[Class2 OK]: " + ENDC
EOF

Step 4: now lets make one main.py which will be execute once to use Class1 and Class2 from 2 different files

$ cat > main.py <<\EOF
"""this is how we are actually calling class1.py and  from that file loading Class1"""
from class1 import Class1 
"""this is how we are actually calling class2.py and  from that file loading Class2"""
from class2 import Class2

print Class1.OK
print Class2.OK
EOF

Step 5: Run the program

$ python main.py

The output would be

[Class1 OK]: 
[Class2 OK]:
Hassan
  • 800
  • 9
  • 24
  • 5
    And what happens if this doesn't work and main.py can't read class1 or class2?... what are we missing? – darkgaze Oct 04 '16 at 14:41
7

Python 3


Same directory.

import file:log.py

import class: SampleApp().

import log
if __name__ == "__main__":
    app = log.SampleApp()
    app.mainloop()

or

directory is basic.

import in file: log.py.

import class: SampleApp().

from basic import log
if __name__ == "__main__":
    app = log.SampleApp()
    app.mainloop()
5
from user import User 
from dir import Dir 
demas
  • 40,368
  • 53
  • 163
  • 263
  • This worked for me without having __init__.py file for both Python 2.7 and Python 3.6. – imsrgadich Apr 03 '18 at 10:08
  • 2
    @imsrgadich it works as long as you're running python in the directory containing the files. This is an exception. See [this comment](https://stackoverflow.com/questions/4142151/how-to-import-the-class-within-the-same-directory-or-sub-directory#comment27915014_4142178) – Ciprian Tomoiagă Jun 18 '18 at 09:54
4

I'm not sure why this work but using Pycharm build from file_in_same_dir import class_name

The IDE complained about it but it seems it still worked. I'm using Python 3.7

stingMantis
  • 175
  • 2
  • 9
  • 1
    Use absolute path. `from bin.user import User` assuming **bin** is the root directory. Also this works for both python 2 and python 3. – Kaushik Acharya Aug 27 '20 at 15:25
0

For python3

import from sibling: from .user import User
import from nephew: from .usr.user import User

Sully
  • 763
  • 4
  • 10
0

If you have filename.py in the same folder, you can easily import it like this:

import filename

I am using python3.7

kobako
  • 493
  • 3
  • 10
-2

Just too brief, Create a file __init__.py is classes directory and then import it to your script like following (Import all case)

from classes.myscript import *

Import selected classes only

from classes.myscript import User
from classes.myscript import Dir
Hafiz Muhammad Shafiq
  • 6,781
  • 10
  • 49
  • 92
  • 4
    Wildcard imports as seen in this answer are generally considered bad style as described in [PEP 8](https://www.python.org/dev/peps/pep-0008/?#id23). – V02460 Jul 26 '18 at 15:20
-3

Python3

use

from .user import User inside dir.py file

and

use from class.dir import Dir inside main.py
or from class.usr import User inside main.py

like so

icharis
  • 51
  • 1
  • 2
  • 4
    This answer doesn't really add anything more than the other answer already do, and has no explanation. Is there some way you could [edit your answer](https://stackoverflow.com/posts/59201996/edit) to add to or improve it? Because otherwise, it stands to be downvoted [like this answer was](https://stackoverflow.com/a/57635519/11384392) or removed entirely. – Das_Geek Dec 05 '19 at 19:44
-4

to import from the same directory

from . import the_file_you_want_to_import 

to import from sub directory the directory should contain

init.py

file other than you files then

from directory import your_file

  • 4
    I don't think this answer adds anything that other answers did not, and also is not a comprehensive summary of the other answers. So I wonder why you wrote it – lucidbrot Sep 04 '19 at 06:45