3
2
記事投稿キャンペーン 「2024年!初アウトプットをしよう」

Pythonでライブラリやクラスの使い方を知りたい。

Last updated at Posted at 2024-01-04

はじめに

importしたライブラリをいざ使う時、どういうファンクションや、メンバーがあるのか?を知る方法を調査してみた。

目次

__doc__

importしたモジュールにdocstringが埋め込まれていれば、__doc__でモジュールのドキュメントを確認できる。例えばpandasの場合は

doc_test.py
import pandas

print(pandas.__doc__)

'''
pandas - a powerful data analysis and manipulation library for Python
=====================================================================

**pandas** is a Python package providing fast, flexible, and expressive data
structures designed to make working with "relational" or "labeled" data both
easy and intuitive. It aims to be the fundamental high-level building block for
doing practical, **real world** data analysis in Python. Additionally, it has
the broader goal of becoming **the most powerful and flexible open source data
analysis / manipulation tool available in any language**. It is already well on
its way toward this goal.

Main Features
-------------
Here are just a few of the things that pandas does well:

  - Easy handling of missing data in floating point as well as non-floating
    point data.
  - Size mutability: columns can be inserted and deleted from DataFrame and
    higher dimensional objects
    ・・・・・省略
'''

自作の関数やクラス内にdocstringを書いておけば、___doc__で呼び出せばhelpになる。

doc_test.py
def func_1(a,b,c):
	'''
関数名:func_1()
引数:a,b,c
戻値:a+b+c
	'''
	return a+b+c

print(func_1.__doc__)

戻る

__dict__

モジュールの中身全てを辞書型で返してくれる。どういう関数や変数を持っているのか?などの確認ができそう。ただ、ものすごいデータ量を出力されるので、結果を何かしらフィルタして使う必要がある。

dict_test.py
import pandas

# pandas の __dict__ を辞書型で出力
for k,v in pandas.__dict__.items():
	print(f'{k=}:{v=}')
 
'''
k='__name__':v='pandas'
k='__doc__':v='\npandas - a powerful data analysis and manipulation library for Python\n=====================================================================\n\n**pandas** is a Python package providing fast, flexible, and expressive data\nstructures designed to make working with "relational" or "labeled" data both\neasy and intuitive. It aims to be the fundamental high-level building bloc
    ・・・・・省略
k='show_versions':v=<function show_versions at 0x0000023AE9B6F0D0>
k='ExcelFile':v=<class 'pandas.io.excel._base.ExcelFile'>
k='ExcelWriter':v=<class 'pandas.io.excel._base.ExcelWriter'>
k='read_excel':v=<function read_excel at 0x0000023AE9BF6B80>
k='read_csv':v=<function read_csv at 0x0000023AE9BEC940>
k='read_fwf':v=<function read_fwf at 0x0000023AE9BECF70>
k='read_table':v=<function read_table at 0x0000023AE9BECB80>
    ・・・・・省略
'''

戻る

inspect (これが便利)

import inspectで呼び出すと使えるライブラリ。モジュール、クラス、メソッド、関数、に関する情報を取得するための機能を提供している。と説明がある。

👇でpandas.__dict__と同じ結果だった。

inspect_test.py
import pandas
import inspect

for k,v in inspect.getmembers(pandas):
	print(f'{k}:{v}')

inspectにはフィルタ機能があり、たとえば関数だけ抜きだしたい場合はinspect.isfunctionを指定すると関数だけ抜き出すことができる。ほかにも is...というパラメータがあるので抜き出したいものだけフィルタすることはできそう。

inspect_test.py
import pandas
import inspect


for k,v in inspect.getmembers(pandas, inspect.isfunction):
	print(f'{k}:{v}')

'''
    ・・・・・省略
read_csv:<function read_csv at 0x000002131E8CC940>
read_excel:<function read_excel at 0x000002131E8D5B80>
read_feather:<function read_feather at 0x000002131E8F7D30>
read_fwf:<function read_fwf at 0x000002131E8CCF70>
read_gbq:<function read_gbq at 0x000002131E9050D0>
read_hdf:<function read_hdf at 0x000002131E9A43A0>
read_html:<function read_html at 0x000002131E913310>
read_json:<function read_json at 0x000002131E937CA0>
read_orc:<function read_orc at 0x000002131E913430>
read_parquet:<function read_parquet at 0x000002131E93D9D0>
read_pickle:<function read_pickle at 0x000002131E94F280>
read_sas:<function read_sas at 0x000002131E9BC700>
read_spss:<function read_spss at 0x000002131E94FF70>
read_sql:<function read_sql at 0x000002131E9D1790>
    ・・・・・省略
'''

関数の引数が知りたい場合はinspect.getfullargspec(func)を使えば引き出せる。funcの設定にはひと手間必要。単に関数名を入れるだけではだめで、getattr()を使って関数を呼び出してあげる必要がある。初めて使うライブラリの引数に何があるのか?を調べるのに便利。

inspect_func_test.py
import pandas
import inspect


for k,v in inspect.getmembers(pandas, inspect.isfunction):
	print(f'{k}:{v}')
	# args_list = FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)
	args_list = inspect.getfullargspec( getattr(pandas, k) )
	print(f'args          :{args_list[0]}')
	print(f'varargs       :{args_list[1]}')
	print(f'varkw         :{args_list[2]}')
	print(f'defaults      :{args_list[3]}')
	print(f'kwonlyargs    :{args_list[4]}')
	print(f'kwonlydefaults:{args_list[5]}')
	print(f'annotations   :{args_list[6]}')
	print('\n')
	
'''
    ・・・・・省略
read_excel:<function read_excel at 0x000002497CCF6B80>
args          :['io', 'sheet_name']
varargs       :None
varkw         :None
defaults      :(0,)
kwonlyargs    :['header', 'names', 'index_col', 'usecols', 'squeeze', 'dtype', 'engine', 'converters', 'true_values', 'false_values', 'skiprows', 'nrows', 'na_values', 'keep_default_na', 'na_filter', 'verbose', 'parse_dates', 'date_parser', 'thousands', 'decimal', 'comment', 'skipfooter', 'convert_float', 'mangle_dupe_cols', 'storage_options']
kwonlydefaults:{'header': 0, 'names': None, 'index_col': None, 'usecols': None, 'squeeze': None, 'dtype': None, 'engine': None, 'converters': None, 'true_values': None, 'false_values': None, 'skiprows': None, 'nrows': None, 'na_values': None, 'keep_default_na': True, 'na_filter': True, 'verbose': False, 'parse_dates': False, 'date_parser': None, 'thousands': None, 'decimal': '.', 'comment': None, 'skipfooter': 0, 'convert_float': None, 'mangle_dupe_cols': True, 'storage_options': None}
annotations   :{'return': 'DataFrame | dict[IntStrT, DataFrame]', 'sheet_name': 'str | int | list[IntStrT] | None', 'header': 'int | Sequence[int] | None', 'names': 'list[str] | None', 'index_col': 'int | Sequence[int] | None', 'usecols': 'int | str | Sequence[int] | Sequence[str] | Callable[[str], bool] | None', 'squeeze': 'bool | None', 'dtype': 'DtypeArg | None', 'engine': "Literal[('xlrd', 'openpyxl', 'odf', 'pyxlsb')] | None", 'converters': 'dict[str, Callable] | dict[int, Callable] | None', 'true_values': 'Iterable[Hashable] | None', 'false_values': 'Iterable[Hashable] | None', 'skiprows': 'Sequence[int] | int | Callable[[int], object] | None', 'nrows': 'int | None', 'keep_default_na': 'bool', 'na_filter': 'bool', 'verbose': 'bool', 'parse_dates': 'list | dict | bool', 'date_parser': 'Callable | None', 'thousands': 'str | None', 'decimal': 'str', 'comment': 'str | None', 'skipfooter': 'int', 'convert_float': 'bool | None', 'mangle_dupe_cols': 'bool', 'storage_options': 'StorageOptions'}
    ・・・・・省略
'''

自作で作ったclassも使える。今後Pythonでコードを書いていく上で活躍しそう。

import inspect

#---------------------------------------
# 自作 class
#---------------------------------------
class cls_test:
	#doc
	'''
これはテストです。
	'''
	
	# 変数
	val_num = 0
	val_str = ''
	
	# 初期化
	def __init__(self):
		self.val_num = 100
		self.val_str = 'abc'

	# メソッド
	def method_num(self,num):
		return self.val_num * num

	# メソッド
	def method_str(self,str='bbb'):
		return self.val_str + str


#---------------------------------------
#関数抜き出し
#---------------------------------------
for k,v in inspect.getmembers(cls_test, inspect.isfunction):
	print(f'{k}:{v}')
	# args_list = FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)
	args_list = inspect.getfullargspec( getattr(cls_test, k) )
	print(f'args          :{args_list[0]}')
	print(f'varargs       :{args_list[1]}')
	print(f'varkw         :{args_list[2]}')
	print(f'defaults      :{args_list[3]}')
	print(f'kwonlyargs    :{args_list[4]}')
	print(f'kwonlydefaults:{args_list[5]}')
	print(f'annotations   :{args_list[6]}')
	print('\n')

'''
__init__:<function cls_test.__init__ at 0x000001C64B5F0940>
args          :['self']
varargs       :None
varkw         :None
defaults      :None
kwonlyargs    :[]
kwonlydefaults:None
annotations   :{}


method_num:<function cls_test.method_num at 0x000001C64B7FF430>
args          :['self', 'num']
varargs       :None
varkw         :None
defaults      :None
kwonlyargs    :[]
kwonlydefaults:None
annotations   :{}


method_str:<function cls_test.method_str at 0x000001C64B7FF4C0>
args          :['self', 'str']
varargs       :None
varkw         :None
defaults      :('bbb',)
kwonlyargs    :[]
kwonlydefaults:None
annotations   :{}
'''

戻る

以上

3
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2