Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions python-docstrings/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# How To Write Docstrings in Python

This folder provides the code examples for the Real Python tutorial [How To Write Docstrings in Python](https://realpython.com/how-to-write-docstrings-in-python/).
33 changes: 33 additions & 0 deletions python-docstrings/classes_docstring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Potion:
"""
Represents a magical potion composed of various ingredients.

Attributes
----------
name : str
The name of the potion.
ingredients : list of str
A list of ingredients used in the potion.
potency : int
The strength level of the potion.

Methods
-------
brew():
Completes the potion and sets its potency.
describe():
Returns a human-readable summary of the potion.
"""

def __init__(self, name, ingredients):
self.name = name
self.ingredients = ingredients
self.potency = 0

def brew(self):
"""Simulate brewing the potion by calculating potency."""
self.potency = len(self.ingredients) * 10

def describe(self):
"""Return a string describing the potion and its strength."""
return f"{self.name} (Potency: {self.potency})"
4 changes: 4 additions & 0 deletions python-docstrings/docstring_format.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
def determine_magic_level(magic_number):
"""
Multiply a wizard's favorite number by 3 to reveal their magic level.
"""
17 changes: 17 additions & 0 deletions python-docstrings/function_docstring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
def enchant_wand(wand_type, level=1):
"""
Enhance a wand with magical properties.

Args:
wand_type (str): The type of wand to enchant.
level (int, optional): The enchantment level. Defaults to 1.

Returns:
str: A message confirming the enchantment.

Raises:
ValueError: If the enchantment level is invalid.
"""
if level < 1:
raise ValueError("Enchantment level must be at least 1.")
return f"{wand_type.title()} enchanted to level {level}!"
3 changes: 3 additions & 0 deletions python-docstrings/get_potter_books.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from books import get_harry_potter_books

print(get_harry_potter_books().__doc__)
12 changes: 12 additions & 0 deletions python-docstrings/google_style.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def get_magic_items(user_id, include_potions=False):
"""
Retrieve a list of magical items for a specific user.

Args:
user_id (int): The ID of the user whose items should be retrieved.
include_potions (bool, optional): include a potions option.

Returns:
list[str]: A list of item names associated with the user.
"""
return ["wand", "cloak", "crystal ball"]
8 changes: 8 additions & 0 deletions python-docstrings/inconsistent_format.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def summon(spell, caster):
"""Summons a creature.
Parameters:
spell - name of the spell
caster: name of the caster
Return:
The summoned creature
"""
11 changes: 11 additions & 0 deletions python-docstrings/inconsistent_format_fix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def summon(spell, caster):
"""
Summons a creature using the given spell.

Args:
spell (str): The name of the summoning spell.
caster (str): The name of the person casting the spell.

Returns:
str: The name of the summoned creature.
"""
12 changes: 12 additions & 0 deletions python-docstrings/magic_spells.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def undo_spell(spell):
"""
Reverses characters in a spell incantation thereby undoing a spell.

Example:
>>> undo_spell("Expelliarmus")
"sumraillepxE"

>>> undo_spell("Lumos")
"somuL"
"""
return spell[::-1]
10 changes: 10 additions & 0 deletions python-docstrings/magical_characters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""A magical module for adding and listing magical characters."""


def add_characters(magical_being):
"""Add a new magical character."""
return f"You've added {magical_being} to the magical beings record"


if __name__ == "__main__":
print(add_characters("Gandalf"))
3 changes: 3 additions & 0 deletions python-docstrings/math_doc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import math

print(math.__doc__)
3 changes: 3 additions & 0 deletions python-docstrings/math_help.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import math

help(math)
8 changes: 8 additions & 0 deletions python-docstrings/minimal_return_details.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def generate_shield(strength):
"""
Generates a magical shield based on input strength.

Args:
strength (int): Strength level.
"""
return f"Shield with strength {strength}"
10 changes: 10 additions & 0 deletions python-docstrings/minimal_return_details_fix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
def generate_shield(strength):
"""
Generates a magical shield based on input strength.

Args:
strength (int): The strength level of the shield.

Returns:
str: A human-readable description of the generated shield.
"""
10 changes: 10 additions & 0 deletions python-docstrings/minipotion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from classes_docstring import Potion


class MiniPotion(Potion):
pass


help(MiniPotion)
print(MiniPotion.__doc__)
print(MiniPotion.brew.__doc__)
10 changes: 10 additions & 0 deletions python-docstrings/minipotion_overide_docstring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from classes_docstring import Potion


class MiniPotion(Potion):
"""Represents a mini magical potion composed of tiny ingredients."""

pass


print(MiniPotion.__doc__)
14 changes: 14 additions & 0 deletions python-docstrings/multi_line_docstring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
def get_harry_potter_books(publication_year, book_name):
"""
Retrieve a Harry Potter book by its publication year and name.

Parameters:
publication_year (int): The year the book was published.
book_name (str): The name of the book.

Returns:
str: A sentence describing the book and its publication year.
"""
return (
f"The book {book_name} was published in the year {publication_year}."
)
6 changes: 6 additions & 0 deletions python-docstrings/navigation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
"""
This module provides tools for creating and managing magical maps.
Example:
from magic_maps import build_map
build_map(["mandrake", "phoenix feather", "tree bark"], heat_level=3)
"""
17 changes: 17 additions & 0 deletions python-docstrings/numpy_style.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
def brew_potion(ingredients, heat_level):
"""
Brew a potion using selected ingredients and heat.

Parameters
----------
ingredients : list of str
A list of magical ingredients.
heat_level : int
The intensity of the heat used for brewing.

Returns
-------
str
A description of the brewed potion.
"""
return f"A sparkling blue elixir of friendship heated at {heat_level}."
7 changes: 7 additions & 0 deletions python-docstrings/one_line_docstring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import random


def picking_hat():
"""Returns a random house name."""
houses = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]
return random.choice(houses)
24 changes: 24 additions & 0 deletions python-docstrings/restructuredText.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
def cast_spell(wand, incantation, target=None):
"""
Cast a magical spell using a wand and incantation.
This function stimulates casting a spell. With no
target specified, it is cast into the void.

:param wand: The wand used to do the spell-casting deed.
:type wand: str
:param incantation: The words said to activate the magic.
:type incantation: str
:param target: The object or person the spell is directed at (optional).
:return: A string describing the result of the spell.
:rtype: str

:raises ValueError: If the incantation is unknown or the wand fails to work.
"""
valid_incantations = ["Lumos", "Alohomora", "Expelliarmus"]
if not wand:
raise ValueError("You can't cast spells without a wand!")
if incantation not in valid_incantations:
raise ValueError("Incantation not recognozed.")
if target:
return f"{incantation} hits {target} with magic speed!"
return f"{incantation} is cast into the void...sparkles shimmer faintly"
3 changes: 3 additions & 0 deletions python-docstrings/vague_descriptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
def brew(item):
"""Does something with the item."""
pass
10 changes: 10 additions & 0 deletions python-docstrings/vague_descriptions_fix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
def brew(potion_ingredients):
"""
Mixes the provided ingredients to brew a potion.

Args:
potion_ingredients (list of str): Ingredients needed to brew the potion.

Returns:
str: The name of the completed potion.
"""