Answer Structure Guide

Basics

The basic structure for a good Kite Answer is:

  1. Title
  2. Further explanation of the question
  3. One or more solutions, each containing a heading, an explanation, and code sample(s)
  4. A "Background information" section, if needed
  5. An "Other Solutions" section, if needed

This guide also describes Callouts.

Primary structure

1. Title

Titles should state a question about Python coding, usually in the form of How to....

Titles should mention Python, unless it mentions some well-known Python framework such as Django or Flask.

Titles should be in sentence case.

Examples

WRONG

How to write a list comprehension

RIGHT

How to write a list comprehension in Python

RIGHT

How to set the URL structure in Flask

RIGHT

The difference between del, pop, and remove in Python

Titles should use singular nouns, unless a plural noun is specifically needed.

Examples

WRONG

How to create dictionaries in Python

RIGHT

How to create a dictionary in Python

RIGHT

How to create a list of dictionaries in Python

Titles should use inline code for Python keywords, but not for concepts that span many languages.

Examples

WRONG

The difference between delete, remove, and pop in Python

RIGHT

The difference between del, pop(), and remove() in Python

WRONG

How to create a dict in Python

RIGHT

How to create a dictionary in Python

Use How to... instead of How do I...

Examples

WRONG

How do I create a dictionary in Python

RIGHT

How to create a dictionary in Python

2. Further explanation of the question

Always include an explanation of the question covered. Your explanation can include context such as:

  • What is it this answer describes how to do? (if a simple example can fit into a sentence, great!)
  • Why/when might someone want to do this?
  • More details about the scope of the problem being solved. What does every solution include or exclude?
Examples

For example if your topic is merging two DataFrames in Pandas, your explanation may be:

Two DataFrames can be merged to produce a unified DataFrame. The result will contain columns from each input. Rows are joined based on overlapping values from columns called "keys." Rows which are present in one DataFrame but not another will be dropped.

If your topic is plotting a horizontal line in Matplotlib, your explanation may be:

Plots may contain horizontal lines. These may represent concepts like minimums, maximums, or averages.

If your topic is computing the median of a list of values, your explanation may be:

The median of a list of numbers separates the higher half from the lower half of items.

In a sorted list with an odd number of items, the median will be the middle element. In a sorted list with an even number of items, the median is typically chosen by averaging the two middle elements.

In the case of generating a list of consecutive numbers:

Generating a list of consecutive numbers like [1, 2, 3] is straightforward in Python.

This case is a little difficult because the title explains in a pretty unambiguous way what we're doing. The [1, 2, 3] example is helpful, but the "...is straightforward in Python" is a bit forced. The best we can say for it is that it may make a Google searcher likely to click on our result because it promises an easy answer.

3. One or more solutions

Each solution contains: a heading, an explanation, a code sample, and possibly further explanation and code samples.

Solution headings

Writing headings

Start each solution with a second-level heading (##) describing the approach taken by the solution.

General guidelines:

  • Headings should summarize the solution.
  • Headings should be full sentences, but don't add a period or other punctuation to the end.
  • Headings should include keywords that someone might have searched for.
  • Liberally repeat words across your answer title and headings.
Examples

For example, if you're showing how to compute the median of a list, your first solution may have the heading:

## Use `statistics.median()` to compute the median of a list".
Short headings

Each solution in Kite Answers gets a normal heading, which is several words long, and a short heading.

Short headings are used for two things:

  1. To generate meta description tags, which search engines will use for search result snippets, and
  2. To generate a table of contents at the top of the answer when there are multiple solutions.

Write short descriptions by summarizing the full solution heading in 1-4 words.

For example the short heading for the solution heading above would probably be "Use statistics.median()". Do not add links (for example kite-sym links) to short headings.

Specifying the short heading requires a bit of added structure to your answer.

First, add an anchor tag to your solution heading, like so:

## Use `statistics.median()` to compute the median of a list". {#use-statistics-median}

Make anchor tags by stripping special characters from your short heading and converting spaces to dashes. In this case "Use statistics.median()" becomes #use-statistics-median.

After adding your anchor tag, put a "front matter" at the beginning of your answer like so:

headers:
    use-statistics-median: Use `statistics.median()`
---
[the rest of your answer goes here, starting with the title]

The front matter is a YAML formatted data structure. For now it is only used to specify the short headings.

Give each solution its own line after the headers: line. Start it with four spaces, then type the anchor tag for the solution, then a : and the short heading text.

Only specify short headings for solutions. Don't specify them for a Background information section if your answer has one.

So in summary, create short headings by:

  1. Adding an anchor tag to each solution
  2. Adding a front matter to the answer with a headers: line, lines for each of your solutions specifying the short heading text, and then a line with three dashes.

Solution explanation and code samples

Then explain the solution. The explanation will repeat in words what the code sample does in code, clarifying anything that would be confusing to a beginner in a concise manner.

First, if a concept used in code is not clear given the scope of knowledge assumed for the question, concisely explain it.

Then explain each non-trivial line of code with these conventions:

  • If the code is a syntax such as using a for-loop or an if statement, use the following template "Use the ... syntax ... to ...".
Syntax Usage Example

For example, if you're describing how to iterate through each element of a list, the sentence for that line may be:

Use the for loop syntax `for element in list` to iterate through every element in `list`.
  • If the code is a function call, use the following template: "Call `function_call(parameter)` with `parameter` as ... to return ...".
Function Call Example

For example, if you're describing how to return whether a string is a digit or not, the sentence for that line may be:

"Call `str.isdigit(element)` with `element` as a string to return `True` if `element` is a digit."
  • Always explain what parameters are and how they are used. Use the following conventions to do so:

    • The parameter names used in code description should be generic and mirror those used for the function call in Kite documentation.
    • Only format words that refer directly to parameters in the function calls or syntax as inline code.
    • Words like tuple and list are, unless they are referring directly to a parameter in code, general concepts and do not need to be formatted as inline code.
  • Using transition words such as "then" is not necessary as it is assumed that you are explaining the code step by step.

Always describe the solution before demonstrating it with code. If you explain the code sample's output, though, do so after the code.

See the Code Style Guide for guidelines on how to write code samples.

Multiple approaches in a single solution

If there are multiple ways to perform an operation, choose a level of complexity that matches the skill level of the question.

However, questions may arise from both advanced and beginner users. If there is a significantly more elegant/compact solution that uses advanced language features, you should first provide a simple solution that illustrates the mechanism, then provide a compact, advanced solution.

This approach provides a solution to any level of user, and offer beginner users a chance to learn advance features of Python.

Examples

For example: "How to check if a string contains a number in Python"

In this case, a single solution "Use str.isdigit to check if any character is a number" could be implemented either simply in a for loop, or more elegantly using map. Include the simple answer first, and the elegant answer under the same solution header with intermediary text explaining the difference. This way, either user can find their preferred solution in a copy/paste-ready format.

## Use `str.isdigit` to check if any character is a number

Iterate through each character of the string. Check if each character is a digit
by calling `str.isdigit()` on each character.
s = "abc1"
contains_number = False
for character in s:
if character.isdigit():
    contains_number = True
print(contains_number)
Use map and any for a more compact implementation.
s = "abc1"
contains_number = any(map(str.isdigit, s))
print(contains_number)

When listed under the same solution header, the core mechanism of the solution should be the same.

In the previous example, both solutions use str.isdigit().

For multiple solutions, the order should ramp from least to most complex.

When including multiple levels of solutions, the explanation should be scoped to the level of the solution. I.E. if using a list comprehension in an advanced solution, the explanation does not need to explain how they work and can assume this knowledge on behalf of the reader.

Multiple solutions

Sometimes, there is more than one way to do something.

In these cases, create an h2 heading for each possible solution.

When to include multiple solutions

Distinguish between the "what" and the "how" of the solution.

  • "How": There are multiple equivalent ways to perform an operation, i.e. via recursion or a loop. Choose the best solution for the experience level implied by the question and list one solution.

  • "What": The question encompasses several distinct operations. These should be listed as separate solutions.

For example:

  • In a question about adding items to a collection, it would make sense to show both how to add a single item, as well as how to add multiple items at once as separate solutions.

  • In a question with multiple interpretations, answer each interpretation in a separate solution. For example, "How to assign multiple variables at once in Python"

  • Meaning 1: "how to assign multiple variables to a single value" i.e, a=b=c=1

  • Meaning 2: "how to assign multiple values to multiple variables" i.e, (a,b) = (1,2)

  • If a question can be solved by two distinct mechanisms that offer different functionality. I.e. using builtins vs a more powerful tools such as numpy or regular expressions. In most cases, this will be listed in Other solutions unless the question invokes common and distinct use cases.

Examples
## Use `isdigit()` within a list comprehension over the string's characters
(...)

## Use a regular expression to filter non-digits from a string
(...)

Order the solutions from most recommended to least recommended. Show the best (or most "Pythonic") way of doing it first.

When including multiple solutions, start each solution by explaining when it should or shouldn't be used.

Examples

For example, a question about type checking might use isinstance as the first solution, followed by type and __class__().

It is a good idea to include alternate approaches (as long as they work), even if they are not recommended. This is especially true if several StackOverflow answers include them.

Taken together, headings should summarize the high level "story" of an answer.

Examples

For example, if there are two solutions which each apply in different cases, that should be captured in the headings.

## Use multiple equal signs to assign a value to multiple variable names
(...)

## Use tuple unpacking to assign multiple values to multiple variable names
(...)

4. Other solutions (optional)

Most answers will have one canonical solution, however some specialized use cases may benefit from alternative answers.

Kite Answers should not be an exhaustive source of all possible solutions. If multiple solutions exist, we should be opinionated and present the best overall answer. However, if alternative solutions are the best solution in some cases, but not often enough that we are including them as solution sections, we should at least highlight them and provide a reference.

Examples

For example:

  • The answer uses the standard library, but a specialized 3rd party library provides a more performant implementation. The performance advantages aren't important often enough to justify covering the library in a full solution section.

The Other solutions section is a brief footnote on when the other solution may be necessary and a Further reading link to additional resources.

This section serves two purposes:

  1. To ensure that Kite Answers is a definitive, one-stop shop for any given question. If we do not directly provide the answer the user is looking for, we should direct them to further resources so that they do not need to return to Google.

  2. To provide stubs for future expansions to Kite Answers.

An entry consists of 3 elements:

  1. A descriptive sentence fragment, following the style and rules of a solution header, but without restating the application. For example, "Use a regular expression", not "Use a regular expression to filter digits out of a string".

  2. One or many bullet point "Notes" which explain when to use the alternate solution. This may include pros and cons, specialized use cases, or any information the author deems relevant. This section purposefully broad to cover a wide range of use-cases.

  3. A terminal bullet point starting with Further reading: in bold and a link to one or more external resources.

Examples
## Other solutions

Use `numpy.median()`
- This solution is more performant for large datasets. However, it requires use of the NumPy library.
- **Further reading:** See documentation for [numpy.median()](https://kite.com/python/docs/numpy.median)

Compute the median manually
(...)

5. Background information (optional)

Most Answers will not require this section, but many advanced topics will benefit from its inclusion.

Examples

Some examples:

  • An answer on type checking might explain why type checking is not typically done in Python. This section would explain (and link to the documentation for) Python's duck typing system and its EAPF philosophy

  • An answer on list comprehension might show examples of nested list comprehensions, set and generator comprehensions, and explain when it is better to use a comprehension or another construct such as a for loop.

  • An answer on lambda functions might show how a lambda function is equivalent to a named function, and warn readers about when a lambda function may impede clarity.

No article requires a section exploring the topic in detail. If you are unsure if one would be valuable, or if you do not feel qualified to write it, do not include it.

However, if you feel strongly that the reader would benefit from further explanation, and you feel qualified to write that explanation, you should feel empowered to do so. (If your editor disagrees, they will simply remove it. If your judgement is consistently off, they will ask you to stop including it in the future.)

(As always, use sentence casing for headings. Do not use "Background Information".)

Annotations

Annotations are a markup of inline code comments. They are rendered alongside the code, but have access to full text formatting capability, including backticks and kite-sym links. The rules for markup features follow plaintext: values referenced in the code should be in backticks, functions should be linked via kite-sym and follow the signature guidelines.

Guidelines for use

Annotations should only be used when they are necessary to understand the code. Each line of code does not need to be annotated. Too many annotations clutter the code and reduce readability.

For longer solutions, they should be used to add landmarks to the code and illustrate key components of the solution.

Format

Annotations appear above the line of code that they reference, preceded by "# ". Annotations are indented to the level of the line that they reference.

Annotations are sentence fragments, striving to be <6 words.

Annotations should be used to demarcate functionality differences (i.e. constructing a pandas array vs querying it), or when code is sufficiently dense and complex (nested for loops).

Examples

These examples are simple cases and would not need annotations in practice. However, they demonstrate the basic syntax and use-cases.

Demarcate functionality

# Construct a 2D `list`
numbers = [[1, 2], [3, 4]]

# Access element at `(0,0)`
number = numbers[0][0]

Explain a single-line operation

total = 0
numbers = [1, 2, 3]
for number in numbers:
    # Add each `number` to `total`
    total = total + number

Explain a loop or iterands

total = 0
numbers = [1, 2, 3]
# Sequentially access each `number`
for number in numbers:
    total = total + number

Preview

Currently, annotation rendering is not supported in the preview engine. The example below shows the intent for how annotations will be rendered, although the exact details may change.

Annotation Preview

Callouts

Callouts are separate pieces of content that are only tangentially related to the answer. They will be presented as a "sidebar". This section describes the types of callouts allowed, when to use them, and how to syntactically specify them.

Further reading

Further reading callouts link the reader to a tutorial where they can learn more about a deeper concept. For example, if you're writing a beginner answer that uses string slices in a fancy way you may want to link to an outside resource explaining string slicing.

The tutorial you link to should be deep and comprehensive. Most StackOverflow pages do not qualify for futher reading links because they are too short.

In the callout, explain what the link will provide, optionally who will find it useful, and what it could be useful for.

Examples
> **Further reading:**
> String slicing is a powerful way to manipulate strings. Read more about string slicing [here](https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3).

It's important to exercise judgement when deciding when to include a further reading link. Only include further reading links when all of the following are true:

  • It doesn't make sense to describe the topic in your answer, because the topic is deep.
  • Most readers won't already understand the topic.
  • Knowing the topic is helpful to using your answer.

For example, in an answer about merging two Pandas DataFrames, you may link to a tutorial about the different kinds of joins because:

  • Describing the variety of types of joins is a deep topic and too long to put in an answer.
  • Most readers won't know about the variety of types of joins.
  • Knowing about the types of joins will be helpful to your readers.

(The types of joins include things like left inner joins, right outer joins, etc. Here is a good guide on the types of joins.)

In an answer about reversing a string using string slicing (s[::-1]), do NOT include a further reading link because understanding string slicing is not important to using your answer. All the user needs to know is to use s[::-1] and they're done.

Warning

Use warnings to call out "gotchas" the reader should be aware of.

Examples
> **Warning:**
> Using a mutable object like a list as the default value for a keyword argument can lead to unintended side effects. Python only initializes the object once and each call of the function will default to the same mutable object.

Callout syntax

You can see the syntax for callouts in the examples above. Special styling will be applied to them.

Do not include code blocks (triple backticks) in callouts.

Do not create callouts that are not Warning or Further reading callouts.