Pythonのプログラムを書いて実行しているときに、行き詰まり、助けを求めることがあります。特定のモジュール、クラス、関数、キーワードなどの意味を知る必要があるかもしれません。良いことに、Pythonにはヘルプシステムが組み込まれています。これは、Python自体の外に助けを求める必要がないことを意味します。
この記事では、Pythonのビルトインヘルプシステムの使い方を学びます。
Pythonのhelp()関数
この関数は、特定のクラス、関数、変数、モジュールなどのドキュメントを取得するのに役立ちます。この関数は、様々なPythonオブジェクトの詳細を取得するためにPythonコンソールで使用されるべきです。
help() 関数へのオブジェクトの渡し方
Python の help()
関数は次のようなシンタックスです。
>>> help(object)
上記のシンタックスでは、object
パラメータはヘルプを得る必要があるオブジェクトの名前です。
例えば、Pythonの print
関数について詳しく知るには、Pythonコンソールで次のコマンドを入力します。
>>> help(print)
出力されます。
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='
', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
dict` クラスのヘルプを得るには、Python コンソールで次のコマンドを入力します。
>>> help(dict)
出力されます。
Help on class dict in module builtins:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
| Methods defined here:
|
| __contains__(self, key, /)
| True if D has a key k, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
...
また、 help()
関数に実際のリストオブジェクトを渡すこともできます。
>>> help(['a', 'b', 'c'])
出力
Help on list object:
class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
...
help()関数にオブジェクトを渡すと、そのオブジェクトのドキュメントやヘルプページが出力されることがわかります。次のセクションでは、
help()`関数に文字列の引数を渡すことについて学びます。
help() に文字列の引数を渡す場合
引数として文字列を渡すと、その文字列は関数、モジュール、キーワード、メソッド、クラス、文書トピックの名前として扱われ、対応するヘルプページが出力されます。文字列の引数として指定するには、文字列を一重引用符または二重引用符で囲みます。
たとえば、次のようになります。
>>> help('print')
出力されます。
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='
', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
print’ を文字列の引数として渡しても、Python の print
関数のドキュメントが表示されます。もう一つの例です。
>>> help('def')
出力
Function definitions
********************
A function definition defines a user-defined function object (see
section *The standard type hierarchy*):
funcdef ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite
decorators ::= decorator+
decorator ::= "@" dotted_name ["(" [parameter_list [","]] ")"] NEWLINE
dotted_name ::= identifier ("." identifier)*
parameter_list ::= (defparameter ",")*
| "*" [parameter] ("," defparameter)* ["," "**" parameter]
| "**" parameter
| defparameter [","] )
parameter ::= identifier [":" expression]
defparameter ::= parameter ["=" expression]
funcname ::= identifier
A function definition is an executable statement. Its execution binds
the function name in the current local namespace to a function object
(a wrapper around the executable code for the function). This
...
ここでは、help()
関数に文字列引数として “def” を渡していますが、関数を定義するためのドキュメントが返されます。
もし、マッチするオブジェクト、メソッド、関数、クラス、モジュールが見つからなければ、その旨が通知されます。例えば
>>> help('qwerty')
出力されます。
No Python documentation found for 'qwerty'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.
文字列に対応するドキュメントが見つからなかったことが通知されます。
時には、あるPythonライブラリで定義されているある関数についてのヘルプを得る必要があるかもしれません。この場合、まずそのライブラリをインポートする必要があります。例えば、Pythonの math
ライブラリで定義されている log
関数のドキュメントを取得する必要がある場合です。この場合、まず math
ライブラリをインポートしてから、以下のように help()
関数を呼び出します。
>>> from math import log
>>> help(log)
出力
Help on built-in function log in module math:
log(...)
log(x[, base])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
help() を引数なしで使用する場合
help()` 関数は引数なしで使用することができます。引数なしでこの関数を実行すると、インタプリタのコンソールで対話型の Python ヘルプユーティリティが起動されます。Pythonのコンソールで次のコマンドを入力するだけです。
>>> help()
このコマンドはPythonのヘルプユーティリティを返し、そこでヘルプを得る必要のあるオブジェクトの名前を入力します。例えば、以下のようになります。
help> print
出力されます。
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='
', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
前のプロンプトに戻るには、”q” を押すだけです。
以下は別の例です。
help> return
出力する。
The "return" statement
**********************
return_stmt ::= "return" [expression_list]
"return" may only occur syntactically nested in a function definition,
not within a nested class definition.
If an expression list is present, it is evaluated, else "None" is
substituted.
"return" leaves the current function call with the expression list (or
"None") as return value.
When "return" passes control out of a "try" statement with a "finally"
clause, that "finally" clause is executed before really leaving the
function.
In a generator function, the "return" statement indicates that the
generator is done and will cause "StopIteration" to be raised. The
returned value (if any) is used as an argument to construct
"StopIteration" and becomes the "StopIteration.value" attribute.
Related help topics: FUNCTIONS
ヘルプユーティリティを終了して Python コンソールに戻るには、”quit” とタイプしてエンターキーを押します。
help> quit
出力
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
>>>
次のセクションでは、カスタムオブジェクトに help()
を定義する方法について説明します。
カスタム関数やクラスのヘルプドキュメントを定義する
docstring (ドキュメント文字列) を定義することで、カスタム関数やカスタムクラスに対する help()
関数の出力を定義することができます。Pythonでは、メソッドのボディに追加された最初のコメント文字列がそのdocstringとして扱われます。コメントは3つのダブルクォートで囲まなければなりません。例えば
def product(a, b):
"""
This function multiplies two given integers, a and b
:param x: integer
:param y: integer
:returns: integer
"""
return a * b
上の例では、product
という名前の関数を定義しています。この関数は、引数/パラメータとして渡された二つの整数値 a
と b
を掛け算します。二重引用符で囲まれたコメントを見てください。
"""
This function multiplies two given integers, a and b
:param x: integer
:param y: integer
:returns: integer
"""
これは、関数 product
の docstring として扱われます。
さて、新しいファイルを作成し、名前を “myfile.py” とします。このファイルに次のコードを追加してください。
def product(a, b):
"""
This function multiplies two given integers, a and b
:param x: integer
:param y: integer
:returns: integer
"""
return a * b
class Student:
"""
Student class in Python. It will store student details
"""
admission = 0
name = ''
def __init__(self, adm, n):
"""
A constructor of the student object
:param adm: a positive integer,
:param n: a string
"""
self.admission = adm
self.name = n
上記の例では、関数、クラス、メソッドに対して docstring が定義されています。
次に、上記のdocstringをPythonコンソールのヘルプドキュメントとして取得する方法を説明します。
まず、関数とクラスの定義をPython環境にロードするために、コンソールでスクリプトを実行する必要があります。これにはPythonの exec()
メソッドを使用します。Pythonのコンソールで次のコマンドを実行します。
>>> exec(open("myfile.py").read())
また、Python IDLEの中でコードを書いた場合は、それを実行するだけでよいです。
これで、Pythonコンソールで globals()
コマンドを実行して、関数モジュールとクラスモジュールが検出されたかどうかを確認することができます。
>>> globals()
私の場合、以下のような出力が得られました。
{'__doc__': None, 'log': <built-in function="" log="", '__builtins__': <module 'builtins'="" (built-in)="", '__spec__': None, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.builtinimporter'="", '__file__': 'C:/Users/admin/myfile.py', 'Student': <class '__main__.student',="" 'product':="" 0x0000000003569b70="" <function="" at="" product=""}
上記の出力にあるように、Student
と product
の両方がグローバルスコープの辞書に含まれています。ここで、help()
関数を使って、Student
クラスと product
関数のヘルプを取得することができます。Pythonのコンソールで次のコマンドを実行するだけです。
>>> help('myfile')
出力されます。
Help on module myfile:
NAME
myfile
CLASSES
builtins.object
Student
class Student(builtins.object)
| Student class in Python. It will store student details
|
| Methods defined here:
|
| __init__(self, adm, n)
| A constructor of the student object
| :param adm: a positive integer,
| :param n: a string
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| admission = 0
|
| name = ''
FUNCTIONS
product(a, b)
This function multiplies two given integers, a and b
:param x: integer
:param y: integer
:returns: integer
FILE
c:usersdminmyfile.py
それでは、product
関数のヘルプを確認してみましょう。
>>> help('myfile.product')
出力されます。
Help on function product in myfile:
myfile.product = product(a, b)
This function multiplies two given integers, a and b
:param x: integer
:param y: integer
:returns: integer
では、Student
クラスのヘルプドキュメントにアクセスしてみましょう。
>>> help('myfile.Student')
出力
Help on class Student in myfile:
myfile.Student = class Student(builtins.object)
| Student class in Python. It will store student details
|
| Methods defined here:
|
| __init__(self, adm, n)
| A constructor of the student object
| :param adm: a positive integer,
| :param n: a string
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| admission = 0
|
| name = ''
出力では、私たちが Student
クラスのために書いたドキュメントを見ることができます。
help() on help()?
help()に引数として
help()` を渡すとどうなるのでしょうか?
>>> help(help())
Welcome to Python 2.7! This is the online help utility.
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/2.7/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".
help>
このユーティリティを使えば、何度も help()
を書かなくても、頻繁に使う方法ならキーワードやモジュール名などを直接CLIに入力するだけでよくなります。通常の help()
を使用するのと同じように実行されますが、処理を短くするユーティリティをスピンアップしています。
help> modules keyword
Here is a list of matching modules. Enter any module name to get more help.
keyword - Keywords (from "graminit.c")
ここでは、モジュールの概要に含まれる keyword
に基づいて、利用可能なモジュールを検索しています。興味深いことに – graminit.c
はそのサマリに keyword
というキーワードを含んでいます。
ユーティリティを終了するには、quit
と入力するだけです。
help> quit
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
結論
Pythonには、モジュール、クラス、関数、キーワードに関するヘルプを得ることができるビルトインシステムが用意されています。このヘルプユーティリティは、REPLにあるPythonの help()
関数を使ってアクセスすることができます。
この関数を呼び出してオブジェクトを渡すと、そのオブジェクトのヘルプページやドキュメントが返されます。引数なしでこの関数を実行すると、ヘルプユーティリティが開かれ、対話形式でオブジェクトに関するヘルプを得ることができます。最後に、カスタムクラスと関数に関するヘルプを得るために、docstringを定義することができます。
。