Skip to content

Instantly share code, notes, and snippets.

@code-yeongyu
Last active February 9, 2025 22:27
Show Gist options
  • Save code-yeongyu/6470c488bfbc9c74748729d79592e343 to your computer and use it in GitHub Desktop.
Save code-yeongyu/6470c488bfbc9c74748729d79592e343 to your computer and use it in GitHub Desktop.
from typing import TYPE_CHECKING, Optional
def import_or_install(package: str, submodule: Optional[str] = None):
try:
if submodule:
module = __import__(f"{package}.{submodule}", fromlist=[submodule])
else:
module = __import__(package)
return module
except ImportError:
print(f"Installing {package}...")
import subprocess
import sys
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
if submodule:
module = __import__(f"{package}.{submodule}", fromlist=[submodule])
else:
module = __import__(package)
return module
prompt = import_or_install("rich", "prompt") # type: ignore
if TYPE_CHECKING: # for type checking
from rich import prompt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment