snippetpythonCritical
How to import the class within the same directory or sub directory?
Viewed 0 times
howdirectorytheimportsamewithinclasssub
Problem
I have a directory that stores all the .py files.
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
bin/
main.py
user.py # where class User resides
dir.py # where class Dir residesI 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.pySolution
Python 2
Make an empty file called
Then just do...
The same holds true if the files are in a subdirectory - put an
So if the directory was named "classes", then you'd do this:
Python 3
Same as previous, but prefix the module name with a
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 DirThe 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.pySo if the directory was named "classes", then you'd do this:
from classes.user import User
from classes.dir import DirPython 3
Same as previous, but prefix the module name with a
. if not using a subdirectory:from .user import User
from .dir import DirCode Snippets
from user import User
from dir import Dirbin/
main.py
classes/
user.py
dir.pyfrom classes.user import User
from classes.dir import Dirfrom .user import User
from .dir import DirContext
Stack Overflow Q#4142151, score: 1269
Revisions (0)
No revisions yet.