Sub topic 2
Set Constraints: Libraries, Style, Scope, and Limits
Assume you can read basic code, run tests, and use a chat-based or editor-integrated AI assistant. A prompt works best when it describes decisions the assistant cannot safely infer.
Set constraints before asking for code
State the language and version, allowed libraries, coding style, scope, and limits. For example, specify whether the assistant may change one function or several files. Include performance requirements and behavior that must remain unchanged.
| Constraint | Example |
|---|---|
| Library | Use only Python’s standard library |
| Style | Add type hints and follow PEP 8 |
| Scope | Change only `slugify.py` |
| Limit | Keep the function under 20 lines |
A vague request such as “make this faster” leaves important choices open. A constrained request gives the assistant a smaller, testable solution space.
Write a Python 3.10 function slugify(text: str) -> str.
Use only the standard library. Change no other files.
Keep the public function signature unchanged.
Replace each run of non-alphanumeric characters with one hyphen.
Return only the function.Show the behavior with examples
Examples turn ambiguous prose into concrete cases. Include normal input, edge cases, and expected output.
Examples:
slugify("Hello, World!") -> "hello-world"
slugify(" Multiple spaces ") -> "multiple-spaces"
slugify("C++ & Rust") -> "c-rust"
slugify("") -> ""The assistant can now infer how to handle punctuation, repeated separators, and empty input. Examples also become test cases.
Ask for the output shape you need
Name the response format explicitly. Request only a function, a unified diff, a complete file, or an explanation followed by tests. This prevents a correct implementation from arriving in a form that is difficult to apply.
Break larger tasks into steps
For a multi-file change, use smaller prompts:
- Ask the assistant to inspect the design and identify affected files.
- Ask for a focused implementation.
- Ask for tests covering the examples and edge cases.
- Ask for a review of failures, scope, and security risks.
This sequence makes errors easier to locate and limits accidental changes.
Exercise
Why should examples appear alongside constraints?
Show answer
They pin down expected behavior and expose edge cases that prose may leave ambiguous.