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
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
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
From python3.3 upwards, __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.
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.
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
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)
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]:
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()
from user import User
from dir import Dir
For Python 3+, suppose you have this structure:
A/
__init__.py
bar.py
foo.py
In your __init__.py file, you can put from . import foo
then you can import foo in bar file
# A/bar.py
from foo import YourClass
The purpose of the __init__.py files is to include optional initialization code that runs as different levels of a package are encountered. everything you put in the __init__.py will be initialized during the package load.
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
For python3
import from sibling: from .user import User
import from nephew: from .usr.user import User
If you have filename.py in the same folder, you can easily import it like this:
import filename
I am using python3.7
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
# My Python version: 3.7
# IDE: Pycharm 2021.1.2 Community
# Have "myLib" in folder "labs":
class Points:
def __init__(self, x = 0, y = 0):
self.__x = x
self.__y = y
def __str__(self):
return f"x = {self.__x}, y = {self.__y}"
# Have "myFile" in (same) folder "labs":
from myFile import Point
p1 = Point(1, 4)
p2 = Point(1, 4)
print(f"p1: {p1}, p2: {p2}")
# Result:
# p1: x = 1, y = 4, p2: x = 1, y = 4
# Good Luck!
Indeed Python does not provide an elegant solution for this everyday use-case. It is especially problematic when you are testing your code that eventually will be delivered as part of a Python package. Here is an approach that has worked for me:
dir
|
file1.py
file2.py
And let's say you want to import file2 from file1.
# In file1.py:
try:
# This works when packaged as Python package
from . import file2
except:
# This works when simply invoking file1 as a module (i.e. python file1)
import file2
# rest of the code ...
I cannot submit an edit for the top answer, so based on some pointers given in comments above, another thing to try out is:
from subfolder.MyClassFile import MyClass
And that's it. Just remember to have an __init__.py empty file in our subfolder.
Just for reference, the solution works if your structure is something like this:
your_project/
__ini__.py
main.py
subfolder/
__init__.py
MyClassFile.py <-- You want this
MyClassFile.py contains the class MyClass.
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
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
Q1: So let's say I have 2 folders and some files in them like this:
root
├── Folder
│ └── file.py
└── Folder1
└── file2.py
Let's say that I have a function in file.py named function() and I want to use it in file2.py. How can I make this happen?
Q2: If file.py contains 5 functions, and I want to use them at any time in file2.py. How do I do that? Is it any different to the answer in the previous question?
function()
function1()
function2()
function3()
function4()
I've tried something with init.py and PYTHONPATH and it didn't work so I've decided to start from the begining.
Found the answer:
#You write this code in file2.py
#This imports the whole file2
import numpy as np
import sys
sys.path.insert(0, "../Folder")
import file.py as U
def main():
s = U.log_sig(0.5)
if __name__ == "__main__":
main
Or if you like to import only function() from file.py then:
from file import function
s = function()
I believe this question must have already been asked but I cannot find an explanation for my problem, sorry if it is a duplicate.
Folder
├── Generator.py
└── modules
├── Function1.py
└── Subfunction.py
Generator.py imports Function1, and Function1 imports Subfunction.
Function1 must be able to be run as a standalone program and as an imported module of Generator.py
It is not a problem itself, as I am using the if __ name__ == "__ main__": to recognize the call type.
But the program fails on importing Subfunction depending on the code I am executing.
# Generator.py
import Function1
# Function1.py
import Subfunction
import modules.Subfunction
The first one works if I execute Function1.py, but it fails if I run Generator.py
The second one works if I execute Generator.py, but it fails if I run Function1.py
I thought imports and relative paths are related to the module where the code is placed, not from a perspective of the top-caller. I tried import .modules.Function1 and import .Function1 but the issue remains.
Is there any elegant way to import Subfunction for both uses, or do I need to include import under if name == main or trap it in try/except?
Edit: all code for #Bastien B
In this shape it works if I execute Function1.py itself.
If I execute Generator.py, I get the ModuleNotFoundError: No module named 'Function1'
# Generator.py
import Function1
print(Function1.Function1_return)
# Function1.py
def Function1_return():
return Subfunction.Subfunction_return()
import Subfunction
if __name__ == '__main__':
print(Function1_return())
# Subfunction.py
def Subfunction_return():
return "this is subfunction"
From what i can see your 'if name ...' is not the problem.
If you use a local venv this should work just fine:
generator.py
from Folder.modules.function1 import Function1_return
print(Function1_return())
Function1.py
from Folder.modules.Subfunction import Subfunction_return
def Function1_return():
return Subfunction_return()
if __name__ == '__main__':
print(Function1_return())
Subfunction.py
def Subfunction_return():
return "this is subfunction"
Depending of your files structure you may have to tweak this a beat
I tried to include file detect_simple.py, but it doesn't work.
Capture screnshoot: https://imgur.com/a/Rku8O1f
My code: in file app.py
__import__("Face_recognition/detect_simple")
from flask import Flask
app = Flask(__name__)
#app.route("/")
def main():
return "OK";
#app.route('/api1')
def api1():
return "OK"
if __name__ == "__main__":
app.run()
run command: python app.py
return error: `Import by filename is not supported.`
So for instance if your app.py is in the top directory and you need to import a module thats in a folder below that directory just use the from subfolder import mymodule.
For example if your directory looks like this:
- FlaskApp
- app.py
- Face_recognition
- detect_simple.py
Then use:
from Face_recognition import detect_simple
To expand on #Jab's answer: your Face_recognition directory must contain a (potentially empty) __init__.py file (with two leading and two trailing underscores) to be recognized by the import system.
Once your tree looks like this:
FlaskApp
|_ app.py
|_ Face_detection/
|_ __init__.py
|_ detect_simple.py
You'll be able to do a
from Face_detection.detect_simple import <whatever>
# or
import Face_detection.detect_simple
# or
from Face_detecting import detect_simple
Keep in mind that the import system is case-sensitive.
On a separate note, please avoid using the __import__ function in almost any case. Prefer the import statement if you're just importing stuff normally, or use importlib.import_module if you have to do programmatic imports (although this shouldn't be the default in most cases).
I have my .py module which is in C:\Python_Projects\MyModules\ with the name button_generator.py.
My code goes something like this:
module_path='C:\\Python_Projects\\MyModules'
module_name='button_generator.py'
sys.path.append(module_path)
try:
limp=importlib.import_module(module_name.split('.')[0])
except:
print 'module import error'
I have tried other versions aswell:
importlib.import_module(module_name) without the split
importlib.import_module('C:\Python_Projects\MyModules\button_generator.py')
importlib.import_module('C:\Python_Projects\MyModules\button_generator')
The folder C:\Python_Projects\MyModules is in my sys.path as I checked during debug.
Why wouldn't the module import?
I suggest you to reorder your project directories and avoid calling other modules which are not in your current directory project. You'll avoid those kind of errors.
For example, let's organize our project directories and folders to look something like this:
MyProjectFolder/
├── main.py
└── modules
├── __init__.py
└── MyLib.py
NB: Don't forget to add an empty file called __init__.py
MyLib.py :
#!/usr/bin/python3
class MyLib:
def __init__(self):
self.say_hello = "Hello i'm in modules/MyLib"
def print_say_hello(self):
print(self.say_hello)
main.py:
#!/usr/bin/python3
# from folder.file import class
from modules.MyLib import MyLib
class MainClass:
def __init__(self):
my_lib = MyLib() # load MyLib class
my_lib.print_say_hello() # access to MyLib methods
### Test
if __name__ == '__main__':
app = MainClass()
In terminal when i run:
$ python3 main.py
output:
Hello i'm in modules/MyLib
So here we have successfully imported the class in modules/MyLib.py into our main.py file.
I found the error:
After treating the ImportError exception by printing it's args, I noticed that button_generator.py had an Import that was not resolving. Basically, button_generator.py could not be imported because it had a wrong import.