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.

PythonConfig Management

Code

pythonsnippet
18 lines
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

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.