Coding
AI Prompt for Writing Functions
Generate clean, working functions with this AI prompt: typed signatures, docstrings, edge cases handled, usage examples, and complexity notes included.
The prompt
Role: You are a senior [LANGUAGE] developer who writes clean, well-documented, production-quality functions. Context: I need a function for: [PURPOSE]. Specification: - Inputs: [INPUTS with types and meanings] - Output: [OUTPUT with type] - Edge cases to handle: [EDGE_CASES] - Code style: [STYLE, e.g. type hints, functional style, PEP8] - Example: input [EXAMPLE_INPUT] should return [EXAMPLE_OUTPUT] Task: 1) Write the complete function with a clear name, typed signature, and docstring explaining parameters, return value, and edge-case behavior. 2) Handle all listed edge cases explicitly. 3) Show 3 usage examples including one edge case. 4) Briefly note the time complexity. Format: The function in a code block first, then usage examples, then the complexity note. Ask the AI to also list the inputs it is LEAST confident about handling, and to mark any assumption it made about ambiguous requirements. Verifying those two lists is faster than debugging a confident-but-wrong implementation. Constraints: No placeholder logic — the function must actually work. Do not add features beyond the spec. Validate inputs and raise meaningful errors for invalid ones.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[LANGUAGE] [PURPOSE] [INPUTS] [OUTPUT] [EDGE_CASES] [STYLE] [EXAMPLE_INPUT] [EXAMPLE_OUTPUT]
Example input
LANGUAGE=Python, PURPOSE=calculate shipping cost from weight, distance and speed tier, INPUTS=weight_kg (float), distance_km (float), tier ('standard'|'express'), OUTPUT=float cost in USD, STYLE=type hints + docstring
How to use this prompt
Write the spec like a contract: inputs with types, outputs, and at least one example. The edge cases you list are where generated code usually fails.
Tips for the best results
- Add 'raise meaningful errors' to the spec when input validation matters.
- Ask for the function in your project's exact style by pasting a sample function as STYLE.
- Generate the tests for it next using the unit-test prompt — they pair perfectly.
Frequently asked questions
What if the generated function is wrong?
Then tighten the spec: add 2-3 examples of tricky inputs and their expected outputs. Precise specs get precise code.
How do I get more defensive code?
Ask it to regenerate with an explicit edge-case list, or switch the STYLE variable to defensive with validation.