Literal Restricts Values At Type Check Time
typing.Literal names an exact set of allowed values for static checkers; at runtime the annotation is documentation with no enforcement.
Code
from typing import Literal
# Literal pins a fixed set of values for static checkers
Mode = Literal["read", "write", "append"]
def open_log(path: str, mode: Mode) -> str:
return f"{path} opened for {mode}"
print(open_log("app.log", "append"))
# At runtime Literal is documentation: the value still passes through
print(open_log("app.log", "wat")) # a static checker rejects this
# Literals work as parameter defaults too
def render(tag: Literal["div", "span"] = "div") -> str:
return f"<{tag}></{tag}>"
print(render(), render("span"))Output
Captured from a sandboxed run of this snippet in the build pipeline.
app.log opened for append
app.log opened for wat
<div></div> <span></span>What the code does
Everything that moves lives in the functions open_log and render.
Watch out for
- All of its symbols are language built-ins — nothing needs fetching.
Applying it
The signature you will call most reads def open_log(path: str, mode: Mode) -> str
open_log is the public entry point; everything else in the file exists to support it.
Statements that matter
def render(tag: Literal["div", "span"] = "div") -> str:
return f"<{tag}></{tag}>"
def open_log(path: str, mode: Mode) -> str:
return f"{path} opened for {mode}"
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Every import resolves inside the standard library — `typing`. The file defines `open_log`, `render` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.