How to import the class within the same directory or sub directory?
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
How to import python class file from same directory?
Since you are using Python 3, which disallows these relative imports (it can lead to confusion between modules of the same name in different packages).
Use either:
from models import finding
or
import models.finding
or, probably best:
from . import finding # The . means "from the same directory as this module"
How to import classes and function from files within the same dir as main.py in Python 3.9?
You have to modify your __init__.py
-File.
In the folder productname
you wanna specify what imports you can run from a module on the same level:
from .car import *
Now you should be able to import your file into your main.py
with:
from car import Car
Importing a file in the same sub-directory of a module
Python follows an execution model very close to regular programs on your computer. The program (or python script) is located somewhere on the $PATH
and any libraries it loads (or python module) is in some different system defined location. Python intends to be installed. Scripts are placed on the PATH and modules are buried somewhere in the python directories.
One exception is that when you run a script, python adds its directory to the python path for modules. So any of its subdirectories that happen to have an __init__.py
become python packages. When you run main.py
, it is a script and subdir
is a package. That lets module1.py
do package relative imports. Interestingly, main.py
itself isn't in a package, the __init__.py
at its level is not imported.
When you run module1.py
as a script, it isn't a package either. So package relative imports no longer work.
The solution is to go through the pain of making all of this an installable package. You define a setup.py and, well, there are multiple options on how to set things up there. setuptools is a good resource. One thing to notice is the console_scripts
parameter that will auto-generate scripts from module entry points.
Its a large hill to climb but as projects go beyond one or two modules, worth the pain.
Importing classes from different files in a subdirectory
Although the names used there are different from what's shown in your question's directory structure, you could use my answer to the question titled Namespacing and classes. The __init__.py
shown there would have also allowed the usepackage.py
script to have been written this way (package
maps to subdir
in your question, and Class1
to myclass01
, etc):
from package import *
print Class1
print Class2
print Class3
Revision (updated):
Oops, sorry, the code in my other answer doesn't quite do what you want — it only automatically imports the names of any package submodules. To make it also import the named attributes from each submodule requires a few more lines of code. Here's a modified version of the package's __init__.py
file (which also works in Python 3.4.1):
def _import_package_files():
""" Dynamically import all the public attributes of the python modules in this
file's directory (the package directory) and return a list of their names.
"""
import os
exports = []
globals_, locals_ = globals(), locals()
package_path = os.path.dirname(__file__)
package_name = os.path.basename(package_path)
for filename in os.listdir(package_path):
modulename, ext = os.path.splitext(filename)
if modulename[0] != '_' and ext in ('.py', '.pyw'):
subpackage = '{}.{}'.format(package_name, modulename) # pkg relative
module = __import__(subpackage, globals_, locals_, [modulename])
modict = module.__dict__
names = (modict['__all__'] if '__all__' in modict else
[name for name in modict if name[0] != '_']) # all public
exports.extend(names)
globals_.update((name, modict[name]) for name in names)
return exports
if __name__ != '__main__':
__all__ = ['__all__'] + _import_package_files() # '__all__' in __all__
Alternatively you can put the above into a separate .py module file of its own in the package directory—such as _import_package_files.py
—and use it from the package's __init__.py
like this:
if __name__ != '__main__':
from ._import_package_files import * # defines __all__
__all__.remove('__all__') # prevent export (optional)
Whatever you name the file, it should be something that starts with an _
underscore character so it doesn't try to import
itself recursively.
Related Topics
Find Nearest Value in Numpy Array
How to Use CSS Selectors to Retrieve Specific Links Lying in Some Class Using Beautifulsoup
Decrypt Chrome Linux Blob Encrypted Cookies in Python
Installing Python 2.7 Without Root
Send Sigint in Python to Os.System
Error: Could Not Build Wheels for Glpk Which Use Pep 517 and Cannot Be Installed Directly
Python: When to Use Pty.Fork() Versus Os.Fork()
How to Return a Value from a Shell Script in a Python Script
How to Make Pip Install to Path on Linux
Listening for Global Key-Combinations in Python on Linux
Is There a Simple Way to Remove Multiple Spaces in a String
Setuid Bit on Python Script:Linux VS Solaris
"E: Unable to Locate Package Python-Pip" on Ubuntu 18.04
How to Determine Pid of Process Started via Os.System
Trying to Simulate Constant Byte Rate. Confusion with Time.Sleep Results
Pairing Bluetooth Devices with Passkey/Password in Python - Rfcomm (Linux)