You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.6中如何导入__init__.py内的函数?解决调用报错

Fixing Import Error for create_app() in manage.py

Hey there! I’ve run into this exact issue before—when you’re trying to import a function from the same directory’s __init__.py, Python’s module resolution can trip you up if you don’t use the right import syntax. Let’s break down the solutions based on your project setup.

First, let’s assume your project structure looks like this (super common for Flask-style apps):

your_project/
    __init__.py  # Contains def create_app(): ...
    manage.py

Solution 1: Relative Import (Cleanest for Package-Safe Code)

Use a relative import to pull create_app from the same directory’s __init__.py:

In manage.py:

from . import create_app

# Now you can use the function normally
app = create_app()

Important note: If you run manage.py directly with python manage.py, you’ll get an error like attempted relative import with no known parent package. That’s because when you run the file as a top-level script, Python doesn’t recognize it as part of a package. Instead, run it as a module from the parent directory of your_project:

python -m your_project.manage

Solution 2: Absolute Import with Path Adjustment (For Direct Script Execution)

If you prefer to run python manage.py directly, you can add the project directory to Python’s system path first, then use an absolute import.

In manage.py:

import os
import sys

# Add the current directory (your_project) to Python's path
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))

# Now import using the package name
from your_project import create_app

app = create_app()

This tells Python where to find your your_project package, even when running manage.py directly.

Solution 3: Install Your Project as an Editable Package (Best for Development)

If you’re working on a larger project, installing it as an editable package lets you import from it anywhere without path hacks. Run this from the parent directory of your_project:

pip install -e .

Now you can just use the absolute import in manage.py without any path adjustments:

from your_project import create_app

app = create_app()

All these methods work with Python 3.6—pick the one that fits how you prefer to run your project!

内容的提问来源于stack exchange,提问作者user504909

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:02:26