Skip to content

Commit a48c355

Browse files
authored
Update I Best Practices.py
1 parent aa7652a commit a48c355

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Writing Functions in Python/I Best Practices.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,5 +54,47 @@ def count_letter(content, letter):
5454
if (not isinstance(letter, str)) or len(letter) != 1:
5555
raise ValueError('`letter` must be a single character string.')
5656
return len([char for char in content if char == letter])
57+
#`````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````
58+
## Retrieving docstrings
5759

60+
# Get the "count_letter" docstring by using an attribute of the function
61+
docstring = count_letter.__doc__
5862

63+
border = '#' * 28
64+
print('{}\n{}\n{}'.format(border, docstring, border))
65+
66+
## Retrieving docstrings 2
67+
68+
import inspect
69+
70+
# Inspect the count_letter() function to get its docstring
71+
docstring = inspect.getdoc(count_letter)
72+
73+
"""add borders"""
74+
border = '#' * 28
75+
print('{}\n{}\n{}'.format(border, docstring, border))
76+
77+
## Retrieving docstrings 3
78+
79+
import inspect
80+
81+
def build_tooltip(function):
82+
"""Create a tooltip for any function that shows the
83+
function's docstring.
84+
85+
Args:
86+
function (callable): The function we want a tooltip for.
87+
88+
Returns:
89+
str
90+
"""
91+
# Get the docstring for the "function" argument by using inspect
92+
docstring = inspect.getdoc(function)
93+
border = '#' * 28
94+
return '{}\n{}\n{}'.format(border, docstring, border)
95+
96+
print(build_tooltip(count_letter))
97+
print(build_tooltip(range))
98+
print(build_tooltip(print))
99+
"""!!!
100+
. But when we want to print the docstring, removing those leading spaces with inspect.getdoc() will look much better."""

0 commit comments

Comments
 (0)