Python help on package

Hello World!

Warren: In the book, we talked a bit about Python’s help system. This is something that can give you help on using Python’s built-in modules and functions as well as external modules and functions. But we didn’t tell you how to add help to your own modules. In this post, we will. I’m going to let Carter take it from here.

Carter: Hi! It’s Carter here. This blog post is a guide to adding help to your Python modules. We will be starting with our TempConv module from Chapter 15:

# this is the file "my_module.py"
# we're going to use it in another program
def c_to_f(celsius):
fahrenheit = celsius * 9.0 / 5 + 32
return fahrenheit

First, let’s see what help() brings up in Python:

>>> import my_module
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named my_module

Oops! We forgot that Python can’t find our module unless it’s in a folder where python can find it. Navigate to this folder in Windows Explorer (or your favourite file browser):

C:\Python25\Lib\site-packages\

Among other things, you should see a Pygame folder, a PythonCard folder, and easygui.py (you might have to scroll down). Save my_module.py there, restart IDLE (or SPE, or Python Shell), and then try importing it again to make sure Python can find it.

Читайте также:  Creating lists in java

Now, let’s see what help() brings:

>>> import my_module
>>> help(my_module)
Help on module my_module:

NAME
my_module

FILE
c:\python25\lib\site-packages\my_module.py

DESCRIPTION
# this is the file "my_module.py"
# we're going to use it in another program

FUNCTIONS
c_to_f(celsius)
# this is the file "my_module.py"
# we're going to use it in another program

Not very user-friendly. Let’s try changing the comments.

# My Module
# Our first module.
def c_to_f(celsius):
#converts celsius to fahrenheit
fahrenheit = celsius * 9.0 / 5 + 32
return fahrenheit

And now restart IDLE again (this is getting annoying…) and call help():

>>>import my_module
>>>help(my_module)
Help on module my_module:

NAME
my_module
FILE
c:\python25\lib\site-packages\my_module.py
DESCRIPTION
#My Module
#Our first module.
FUNCTIONS
c_to_f(celsius)

Huh. Why didn’t c_to_f’s comment appear? The answer is that help() uses strings, but supports comments at the start of the program. Let’s change my_module again:

"""My Module
Our first module."""

def c_to_f(celsius):
"converts celsius to fahrenheit"
fahrenheit = celsius * 9.0 / 5 + 32
return fahrenheit

And now restart IDLE and use help again:

>>> import my_module
>>> help(my_module)
Help on module my_module:

NAME
my_module
FILE
c:\python25\lib\site-packages\my_module.py

DESCRIPTION
My Module
Our first module.

FUNCTIONS
c_to_f(celsius)
converts celsius to fahrenheit

There, now that looks a lot better. Also, Python classes display similar help. Try typing this into my_module:

"""My Module
Our first module."""

def c_to_f(celsius):
"converts celsius to fahrenheit"
fahrenheit = celsius * 9.0 / 5 + 32
return fahrenheit

class SampleObject:
"Sample object"
def __init__(self, number):
"Initializes object"
self.number = number
def addOne(self):
"Adds one to the number"
self.number += 1
>>> import my_module
>>> help(my_module)
Help on module my_module:

NAME
my_module

FILE
c:\python25\lib\site-packages\my_module.py

DESCRIPTION
My Module
Our first module.

CLASSES
SampleObject

class SampleObject
Sample object

Methods defined here:

__init__(self, number)
Initializes object

addOne(self)
Adds one to the number

FUNCTIONS
c_to_f(celsius)
converts celsius to fahrenheit

One more thing: For help() to work correctly, your string also has to be on the first line of your program (or function, or class, or method), and be indented correctly.
And that’s how you can make your modules look great in help()!

Источник

Функция help() в Python: вызов справки

Когда вам нужна помощь в написании программы, использовании модулей, а также для вызова справки рекомендуется использовать функцию help() в Python.

Руководство функции Python help()

Что такое help() в Python?

help() в Python — это встроенный метод, который используется для интерактивного использования. Функция help() используется для получения документации по указанному модулю, классу, функции, переменным и т.д.

Синтаксис

В справочной консоли мы можем указать имена модулей, классов и функций, чтобы получить их документацию.

Теперь перейдите в терминал или консоль CMD и введите следующую команду.

На данный момент версия Python3 является последней, поэтому введите python3, и вы увидите то, что показано ниже.

Теперь введите функцию help().

Теперь мы можем проверить следующие встроенные функции и модули.

Допустим, мы вводим коллекции, а затем получаем следующий вывод в консоли.

Параметры

Метод help() принимает максимум один параметр.

object передается в help()

Введите следующую команду.

Строка передается в качестве аргумента

Если строка передается в качестве аргумента, данная строка ищется как имя модуля, функции, класса, метода, ключевого слова или раздела документации, и печатается страница справки.

Если вы хотите выйти из справочной консоли, введите команду quit.

Определение help() для пользовательского класса и функций

Мы можем определить вывод функции help() для наших пользовательских классов и функций, указав docstring (строку документации).

По умолчанию в качестве строки документации используется первая строка комментария в теле метода. Его окружают три двойных кавычки.

Допустим, у нас есть файл python help_examples.py со следующим кодом.

Источник

How to View Python Package Documentation

Book image

You can use the doc() function whenever needed to get quick help. However, you have a better way to study the packages and libraries located in the Python path — the Python Package Documentation. This feature often appears as Package Docs in the Python folder on your system. It’s also referred to as Pydoc. Whatever you call it, the Python Package Documentation makes life a lot easier for developers.

Opening the Pydoc application

Pydoc is just another Python application. It actually appears in the \Python36\Lib directory of your system as pydoc.py . As with any other .py file, you can open this one with Notebook and study how it works. You can start it by using the Python 3.6 Module Docs shortcut that appears in the Python 3.6 folder on your system or by using a command at the Anaconda Prompt.

You can use Pydoc in both graphical and textual mode. When opening an Anaconda Prompt, you can provide a keyword, such as JSON, and Pydoc displays textual help. Using the -k command-line switch, followed by a keyword such as if, lets you display a list of places where specific keywords appear. To actually start the server, you type Pydoc -b and press Enter. If you need to use a specific port for your browser, add the -p command-line switch with a port number.

The graphical mode of the Pydoc application creates a localized server that works with your browser to display information about the Python packages and libraries. So when you start this application, you see a command (terminal) window open.

As with any server, your system may prompt you for permissions. For example, you may see a warning from your firewall telling you that Pydoc is attempting to access the local system. You need to give Pydoc permission to work with the system so that you can see the information it provides. Any virus detection that you have installed may need permission to let Pydoc continue as well. Some platforms, such as Windows, may require an elevation in privileges to run Pydoc.

Normally, the server automatically opens a new browser window for you. This window contains links to the various packages that are contained on your system, including any custom packages you create and include in the Python path. To see information about any package, you can simply click its link.

Index page Python

Your browser displays a number of links that appear as part of the Index page.

The Anaconda Prompt provides you with two commands to control the server. You simply type the letter associated with the command and press Enter to activate it. Here are the two commands:

  • b : Starts a new copy of the default browser with the index page loaded.
  • q : Stops the server.

When you’re done browsing the help information, make sure that you stop the server by typing q and pressing Enter at the command prompt. Stopping the server frees any resources it uses and closes any holes you made in your firewall to accommodate Pydoc.

Near the top of the web page, you see three links. These links provide quick access to the site features. The browser always begins at the Module Index. If you need to return to this page, simply click the Module Index link.

The Topics link takes you to the page shown below. This page contains links for essential Python topics. For example, if you want to know more about Boolean values, click the BOOLEAN link. The page you see next describes how Boolean values work in Python. At the bottom of the page are related links that lead to pages that contain additional helpful information.

Topics page Python

The Topics page tells you about essential Python topics, such as how Boolean values work.

The Keywords link takes you to the page below. What you see is a list of the keywords that Python supports. For example, if you want to know more about creating for loops, you click the for link.

Keywords page Python

The Keywords page contains a listing of keywords that Python supports.

Typing a search term

The pages also include two text boxes near the top. The first has a Get button next to it and the second has a Search button next to it. When you type a search term in the first text box and click Get, you see the documentation for that particular package or attribute. This is what you see when you type print and click Get.

Get Python

Using Get obtains specific information about a search term.

When you type a search term in the second text box and click Search, you see all the topics that could relate to that search term. The image below shows typical results when you type print and click Search. In this case, you click a link, such as calendar, to see additional information.

Search Python

Using Search obtains a list of topics about a search term.

Viewing the results

The results you get when you view a page depends on the topic. Some topics are brief. However, other topics are extensive. For example, if you were to click the calendar link, you would see a significant amount of information.

extensive info Python

Some pages contain extensive information.

In this particular case, you see related package information, error information, functions, data, and all sorts of additional information about the calendar printing functions. The amount of information you see depends partly on the complexity of the topic and partly on the amount of information the developer provided with the package. For example, if you were to select BPPD_11_Packages from the Package Index page, you would see only a list of functions and no documentation at all.

About This Article

This article is from the book:

Источник

Оцените статью