I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:
Server -server.py -Models --user.py
Here's the contents of server.py:
from sys import path from os import getcwd path.append(getcwd() + "\\models") #Yes, i'm on windows print path import user u=user.User() #error on this line
And user.py:
class User(Entity): using_options(tablename='users') username = Field(String(15)) password = Field(String(64)) email = Field(String(50)) status = Field(Integer) created = Field(DateTime)
The error is: AttributeError: 'module' object has no attribute 'User'
You need to add Python path runtime using the sys. path. append() method will then resolve the importing file's path. Importing files from one folder to another in Python is a tricky task, and by default, you can't do that, and if you try, you will get an error.
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
The most Pythonic way to import a module from another folder is to place an empty file named __init__.py into that folder and use the relative path with the dot notation. For example, a module in the parent folder would be imported with from .. import module .
The easiest way to import a Python module, given the full path is to add the path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.
I believe you need to create a file called __init__.py
in the Models directory so that python treats it as a module.
Then you can do:
from Models.user import User
You can include code in the __init__.py
(for instance initialization code that a few different classes need) or leave it blank. But it must be there.
You have to create __init__.py
on the Models
subfolder. The file may be empty. It defines a package.
Then you can do:
from Models.user import User
Read all about it in python tutorial, here.
There is also a good article about file organization of python projects here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With