On this page
  1. getpass
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Safe Token Acquisition (Env Var → Interactive Prompt Fallback)
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

getpass

Prev: getopt | Up: stdlib_module | Next: gettext
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — getpass
Tags: #public #python3 #stdlib


Import

import getpass

Overview

Prompts for passwords or secrets interactively on a terminal without echoing typed characters (getpass.getpass), and resolves the current OS username (getpass.getuser). Always use getpass.getpass() instead of input() whenever prompting for tokens, passphrases, or passwords.

Quick Start

import getpass

user = getpass.getuser()
assert isinstance(user, str) and len(user) > 0
# Interactive prompt (no echo):
# secret = getpass.getpass("API token: ")

Implementation Walkthrough

1. Safe Token Acquisition (Env Var → Interactive Prompt Fallback)

import getpass
import os
import sys

def get_api_token(env_var: str = "API_TOKEN") -> str:
    if token := os.getenv(env_var):
        return token
    if not sys.stdin.isatty():
        raise RuntimeError(f"{env_var} is not set and stdin is not interactive")
    return getpass.getpass(f"Enter {env_var}: ")

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes