1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pythonのimportはこうも書ける

Last updated at Posted at 2025-11-23

めっちゃ初歩的な内容です🙇

結論:from . import <モジュール名> で同階層全体を指定できる

from . import views
  • 先頭の . は「このファイルと同じディレクトリ階層」を表します。
  • モジュール名を指定するだけで、views.関数名 のようにモジュール名を明示したまま利用できます。

重要: 相対インポートを使うときは、対象ディレクトリがパッケージとして認識されている(__init__.py が置かれている)必要があります。

活用例:Django の urls.pyviews.py を読み込む

from django.contrib import admin
from django.urls import path, include

# 同階層の views.py をまとめて読み込む
from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('post/<int:pk>', views.post_detail, name='post_detail'),
]
  • URL パターンの第二引数に views.post_list のように書けるため、「どこから来た関数か」がひと目でわかります。
  • from .views import post_list と個別にインポートすると、URL 定義だけを見たときにモジュールが判別しづらくなります。views を残したまま書ける方が読み手に親切です。
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?