Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import the class within the same directory or sub directory?

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 
like image 999
Bin Chen Avatar asked Nov 10 '10 07:11

Bin Chen


People also ask

How do I import a class from another folder?

To import files from a different folder, add the Python path at runtime. To add the Python path, use the sys. path. append() method, which includes locations such as the package.

Can you import a class in Python?

In this article, we will see How to import a class from another file in Python. Import in Python is analogous to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import.


2 Answers

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 
like image 90
Amber Avatar answered Sep 27 '22 19:09

Amber


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 
like image 42
ecp Avatar answered Sep 27 '22 17:09

ecp