Sub topic 4
Set constraints: libraries, style, scope, and limits
This chapter assumes you can write a goal and add context, as covered in the earlier chapters. You should also be able to run a Python script and a pytest test. The examples use Python, but the ideas apply to any language.
Why constraints matter
A goal says what you want. Context says where the code will live. Constraints say which solutions are acceptable. Without them, the assistant picks whatever is most common in the code it learned from. That is often a reasonable choice, but it may not be yours.
Take the request "Write a function to clean up titles." The assistant might install a third-party package, return a tuple, rewrite your helper functions, or add logging. Each choice is legitimate for some project. None is guaranteed to fit yours.
A constraint narrows the set of acceptable answers. A good constraint removes a decision you would otherwise have to undo after the response arrives. In practice, constraints fall into four groups.
| Group | What it controls | Example constraint |
|---|---|---|
| Libraries | Which dependencies and language features are allowed | "Use only the Python standard library." |
| Style | How the code reads | "Follow PEP 8, use type hints, no comments except docstrings." |
| Scope | What the assistant may touch | "Change only `parse_date`; do not edit other functions or the signature." |
| Limits | Performance, size, and behavior bounds | "Run in O(n) time; handle inputs up to 1 MB; raise `ValueError` on empty input." |
Library constraints
The most common surprise in generated code is an unexpected dependency. If you do not say which libraries are allowed, the assistant may import a package that is not installed, or one that your team has not approved.
State the rule in one of three forms:
- Allowlist: "Use only
reandunicodedata." - Category rule: "Standard library only."
- Denylist: "Do not use
requests; we usehttpx."
Versions matter too. A library constraint is incomplete if it ignores the runtime. "Python 3.10" tells the assistant that match statements and X | Y type unions are available, and that tomllib (added in 3.11) is not. If you have already given the version as context, repeat it only when it changes what is allowed.
Say what to do when the constraint makes the task hard. For example: "If the task cannot be done with the standard library alone, say so instead of adding a dependency." Without that sentence, an assistant may quietly break your rule to produce a working answer.
Style constraints
Style constraints keep generated code consistent with the code around it. They are most useful when they are concrete and checkable. "Write clean code" gives the assistant nothing to act on. These work better:
- "Follow PEP 8 and keep lines under 88 characters (Black style)."
- "Add type hints to every parameter and return value."
- "Use
snake_casefor functions andPascalCasefor classes." - "No comments; a one-line docstring is enough."
- "Prefer early returns over nested
ifblocks."
If your project has a linter or formatter configuration, name the tool: "The code must pass ruff check with our default settings." The assistant cannot run your configuration unless it has tool access, so you still run the check yourself, but it gives the assistant a target.
Style rules also include what to leave out. Assistants often add explanations, example usage, or error handling you did not request. "Do not add logging or print statements" is a valid constraint.
Scope constraints
Scope constraints matter most when you give the assistant existing code to modify. They answer the question: what may change?
Unscoped edits cause real trouble. You ask for a bug fix in one function, and the response also renames variables, reorders imports, and "improves" a neighboring function. The diff becomes hard to review, and the extra changes may introduce new bugs.
Useful scope constraints include:
- Name the target: "Modify only the
load_configfunction." - Freeze the interface: "Keep the function name, parameters, and return type unchanged."
- Protect other code: "Do not edit the tests or any file other than
config.py." - Exclude extras: "No new features, no refactoring, no renaming."
Scope also means what the task does not include. "Handle only ASCII input; ignore Unicode" is a scope decision. It tells the assistant not to spend complexity on cases you do not need. Writing such exclusions down also records them for the next reader.
Limit constraints
Limits are bounds on behavior. They come in three kinds:
- Performance: time or memory growth, such as "linear time" or "must not load the whole file into memory."
- Input range: the sizes and types the code must handle, such as "up to 100,000 rows" or "
Noneis never passed." - Failure behavior: what happens on bad input, such as "raise
ValueErrorwith a clear message" or "return an empty list; never raise."
Failure behavior is the one people forget, and the assistant fills the gap with a guess. One assistant might return None for bad input and another might raise KeyError. Your calling code expects one specific behavior.
Be careful with performance limits. "Make it fast" is too vague to act on or verify. "Process a 1 million row CSV in under 5 seconds on a laptop" can be measured. If you cannot measure a limit, do not rely on the assistant having met it.
Writing constraints that work
Four habits make constraints more effective.
Make each one testable. Ask yourself how you would check it. "Lowercase the result" is checkable. "Make the output nice" is not.
State what to do, then what to avoid. A positive instruction is easier to follow than a bare prohibition. Compare "Use pathlib for file paths" with "Don't use os.path." Give both when the denylist matters.
Keep them separate and short. Put one rule per line. A long paragraph of rules hides which ones matter, and it makes it harder for you to see which one the assistant ignored.
Keep only the rules that matter. Every constraint you add is something the assistant must satisfy and you must verify. A dozen minor style rules can crowd out the one important rule about scope. List the rules you would reject the response for violating.
Here is the earlier title-cleaning prompt with its constraints written out.
Write a Python 3.10 function slugify(text: str) -> str that converts an article title into a URL slug.
Context: it will be used in a small blog tool; titles are plain ASCII.
Constraints: use only the standard library; lowercase the result; replace each run of non-alphanumeric characters with a single hyphen; no leading or trailing hyphens.
Return only the function, with no explanation.Each constraint here can be checked. "Standard library only" is a library rule. "Lowercase" and "single hyphen" are behavior rules. "No leading or trailing hyphens" is an edge-case rule that would otherwise be left to chance.
How constraints fit with the rest of the prompt
Constraints depend on the goal and the context. The goal decides which constraints are relevant, and the context (language, version, existing code) decides what the constraints can sensibly say. In turn, constraints feed the next pieces of a prompt: examples show the constrained behavior in concrete cases, and the output format controls how the answer is delivered.
When constraints conflict
Constraints can contradict each other, or contradict the goal. "Standard library only" and "parse this YAML file" conflict, because Python's standard library has no YAML parser. "Under 20 lines" and "handle every Unicode edge case" also pull in opposite directions.
Assistants handle conflicts in different ways. Some quietly drop one rule. Some satisfy the letter of a rule and break its intent. Some mention the problem. You cannot rely on the third behavior, so tell the assistant what to do:
- "If two requirements conflict, stop and tell me which ones."
- "Prefer the scope rule over the style rules if they conflict."
Priority statements like these cost one line and save a round of confusion.
Checking constraints automatically
Some constraints can be checked by a script. This turns "did the assistant follow my rules?" into a command you can run. The script below enforces the library rule from the slugify prompt. It parses a Python file and reports any import outside an allowlist.
import ast
import sys
ALLOWED = {"re"}
def disallowed_imports(source: str) -> set[str]:
found = set()
for node in ast.walk(ast.parse(source)):
if isinstance(node, ast.Import):
found.update(alias.name.split(".")[0] for alias in node.names)
elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
found.add(node.module.split(".")[0])
return found - ALLOWED
if __name__ == "__main__":
with open(sys.argv[1], encoding="utf-8") as handle:
bad = disallowed_imports(handle.read())
if bad:
print("Disallowed imports:", ", ".join(sorted(bad)))
sys.exit(1)
print("Imports OK")Save it as check_imports.py and run python check_imports.py slugify_module.py. For the slugify function from the previous prompt, which imports only re, it prints Imports OK. If the assistant had added import unidecode, it would print Disallowed imports: unidecode and exit with status 1.
Other constraints have their own tools:
- Style: run your formatter and linter, such as
black --checkorruff check. - Scope: read the diff with
git diffand confirm only the named function changed. - Behavior limits: write tests for the failure cases, such as a test that empty input raises
ValueError. - Performance: time the code on an input of the stated size.
Constraints you can verify mechanically are the ones worth stating most firmly.
Common mistakes
- Vague constraints. "Keep it simple" and "make it efficient" cannot be checked. Replace them with a measurable rule.
- Constraints buried in prose. If the rule is in the middle of a paragraph, it is easy for the assistant, and for you, to miss. Put rules on separate lines under a "Constraints" label.
- Missing scope rules on edits. If you paste code and ask for a change, say what may not change.
- Assuming the environment. The assistant does not know what is installed or which Python version you run. Name both.
- Over-constraining. If a rule only reflects a preference you would not enforce in review, leave it out.
- Forgetting failure behavior. State what happens on invalid input, or the assistant will choose.
Summary of the practice
Before you send a prompt, scan it with four questions:
- Which libraries and language version are allowed?
- What must the code look like to fit the project?
- What may the assistant change, and what must it leave alone?
- What are the input sizes, error behaviors, and performance bounds?
Write down only the answers that would change whether you accept the response. Then, wherever you can, check them with a tool instead of by eye.
Exercise
You paste a 40-line function parse_price from your project and write: "Fix the bug where prices like '1,299.50' fail to parse. Make it clean and fast." The response fixes the bug but also renames two variables, changes the return type from float to Decimal, and imports babel. Rewrite the prompt's constraints so that none of these three changes would happen, and say which group (libraries, style, scope, limits) each new rule belongs to.
Show answer
Example constraints: (1) "Modify only the body of parse_price; do not rename variables or touch other functions" (scope). (2) "Keep the signature and the float return type unchanged" (scope). (3) "Use only the standard library; if that is not enough, say so instead of adding a dependency" (libraries). The vague "make it clean and fast" should be removed or replaced with checkable rules, such as "follow PEP 8" (style) or "must handle strings up to 20 characters" (limits). Failure behavior could also be added as a limit: "raise ValueError for strings that are not valid prices."
Exercise
A prompt says "Use only the standard library" and also "Read and write the config as YAML." What is the problem, and what one-line instruction would make the assistant's behavior predictable?
Show answer
Python's standard library has no YAML parser, so the two rules conflict. An assistant may quietly add a package such as PyYAML or write a fragile hand-made parser. Adding a line such as "If two requirements conflict, stop and tell me which ones" (or stating a priority, such as "the standard-library rule wins") makes the behavior predictable.