Traceback (most recent call last):
File "/home/labex/project/import_demo/subdir/app.py", line 2, in <module>
import helper
ModuleNotFoundError: No module named 'helper'
## This is the name_error.py file
from helper import greet, farewell
print(greet("Student"))
print(farewell("Student"))
このファイルを実行します。
python3 name_error.py
次のようなエラーが表示されるはずです。
Traceback (most recent call last):
File "/home/labex/project/import_demo/name_error.py", line 2, in <module>
from helper import greet, farewell
ImportError: cannot import name 'farewell' from 'helper' (/home/labex/project/import_demo/helper.py)
## This is the string_utils.py file
def reverse_string(text):
return text[::-1]
def capitalize_words(text):
return ' '.join(word.capitalize() for word in text.split())
メインモジュールmypackage/main_module.pyを作成します。
## This is the main_module.py file
from mypackage.utils.string_utils import reverse_string, capitalize_words
def process_text(text):
capitalized = capitalize_words(text)
reversed_text = reverse_string(text)
return {
"original": text,
"capitalized": capitalized,
"reversed": reversed_text
}
プロジェクトディレクトリにパッケージを使用するスクリプトuse_package.pyを作成します。
cd ~/project
## This is the use_package.py file
import sys
from mypackage.main_module import process_text
result = process_text("hello python world")
print("Text Processing Results:")
for key, value in result.items():
print(f"{key}: {value}")
次に、このスクリプトを実行しましょう。
python3 use_package.py
次のような出力が表示されるはずです。
Text Processing Results:
original: hello python world
capitalized: Hello Python World
reversed: dlrow nohtyp olleh
## This is the module_a.py file
print("Module A is being imported")
## Importing from module B
from module_b import function_b
def function_a():
print("Function A is called")
return "Result from function_a"
module_b.pyという名前のファイルを作成します。
## This is the module_b.py file
print("Module B is being imported")
## Importing from module A
from module_a import function_a
def function_b():
print("Function B is called")
return "Result from function_b"
循環インポートをテストするファイルtest_circular.pyを作成します。
## This is the test_circular.py file
try:
import module_a
module_a.function_a()
except Exception as e:
print(f"Error occurred: {type(e).__name__}")
print(f"Error message: {e}")
次に、このテストスクリプトを実行しましょう。
python3 test_circular.py
循環インポートに関連するエラーが表示されるはずです。
Module A is being imported
Module B is being imported
Error occurred: ImportError
Error message: cannot import name 'function_a' from partially initialized module 'module_a' (most likely due to a circular import)
循環インポートの解決
循環インポートを解決する方法はいくつかあります。
循環依存関係を排除するために、コードを再構築します。
インポート文を関数内に移動して、必要な場合にのみ実行されるようにします。
特定の関数ではなく、モジュールをインポートし、モジュール名を使用して関数にアクセスします。
方法#2 を使用して、循環インポートを修正しましょう。
module_a.pyを更新します。
## Modified module_a.py file
print("Module A is being imported")
def function_a():
print("Function A is called")
## Import inside the function to avoid circular import
from module_b import function_b
print("Calling function_b from function_a")
result = function_b()
return f"Result from function_a with {result}"
module_b.pyを更新します。
## Modified module_b.py file
print("Module B is being imported")
def function_b():
print("Function B is called")
return "Result from function_b"
次に、テストスクリプトをもう一度実行しましょう。
python3 test_circular.py
これで、次のような出力が表示されるはずです。
Module A is being imported
Function A is called
Module B is being imported
Calling function_b from function_a
Function B is called
## This is the use_requests.py file
try:
import requests
response = requests.get('https://api.github.com')
print(f"GitHub API Status Code: {response.status_code}")
print(f"GitHub API Response: {response.json()}")
except ImportError:
print("The requests module is not installed.")
print("You can install it using: pip install requests")
cd ~/project
sudo apt update
sudo apt install python3-venv
仮想環境を作成してアクティブ化します。
python3 -m venv myenv
source myenv/bin/activate
プロンプトが変わり、現在仮想環境内にあることを示します。
仮想環境にパッケージをインストールします。
pip install colorama
test_colorama.pyという名前のファイルを作成します。
## This is the test_colorama.py file
try:
from colorama import Fore, Style
print(f"{Fore.GREEN}This text is green!{Style.RESET_ALL}")
print(f"{Fore.RED}This text is red!{Style.RESET_ALL}")
print(f"{Fore.BLUE}This text is blue!{Style.RESET_ALL}")
except ImportError:
print("The colorama module is not installed.")
print("You can install it using: pip install colorama")
## This is the list_modules.py file
import pkg_resources
print("Installed Python modules:")
for package in pkg_resources.working_set:
print(f"- {package.project_name} (version: {package.version})")