⚠️ 記事内に広告を含みます。

pythonの組み込み関数の確認方法

組み込み関数の一覧を取得する方法

pythonに組み込まれている組み込み関数について

組み込み関数の一覧

pythonには様々なライブラリがありますが、組み込み関数はimportしなくても利用できます。

https://docs.python.org/ja/3/library/functions.html

組み込み関数の一覧はpython上からも確認できます。

#組み込み関数の一覧を表示する
import builtins # builtinsモジュールのインポート

builtinfunctions = dir(builtins)

print(dir(builtins)) #組み込み関数の一覧をリストで取得する

for i in builtinfunctions: #組み込み関数の一覧を一列で表示する
    print(i)
---実行結果---
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 
'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']


ArithmeticError
AssertionError
AttributeError
BaseException
BlockingIOError
BrokenPipeError
BufferError
BytesWarning
ChildProcessError
ConnectionAbortedError
ConnectionError
ConnectionRefusedError
ConnectionResetError
DeprecationWarning
EOFError
Ellipsis
EnvironmentError
Exception
False
FileExistsError
FileNotFoundError
FloatingPointError
FutureWarning
GeneratorExit
IOError
ImportError
ImportWarning
IndentationError
IndexError
InterruptedError
IsADirectoryError
KeyError
KeyboardInterrupt
LookupError
MemoryError
ModuleNotFoundError
NameError
None
NotADirectoryError
NotImplemented
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
PermissionError
ProcessLookupError
RecursionError
ReferenceError
ResourceWarning
RuntimeError
RuntimeWarning
StopAsyncIteration
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TimeoutError
True
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
WindowsError
ZeroDivisionError
__build_class__
__debug__
__doc__
__import__
__loader__
__name__
__package__
__spec__
abs
all
any
ascii
bin
bool
breakpoint
bytearray
bytes
callable
chr
classmethod
compile
complex
copyright
credits
delattr
dict
dir
divmod
enumerate
eval
exec
exit
filter
float
format
frozenset
getattr
globals
hasattr
hash
help
hex
id
input
int
isinstance
issubclass
iter
len
license
list
locals
map
max
memoryview
min
next
object
oct
open
ord
pow
print
property
quit
range
repr
reversed
round
set
setattr
slice
sorted
staticmethod
str
sum
super
tuple
type
vars
zip

これだけの組み込み関数があります。

入力した文字列が組み込み関数か判定する

みればわかりますが、組み込み関数かどうか判定するプログラムも書けます

#組み込み関数の一覧を表示する
import builtins # builtinsモジュールのインポート

builtinfunctions = dir(builtins)

#ユーザ入力した文字列が組み込み関数かどうかを判定する
def is_builtin_function(str):
    if str in builtinfunctions:    #in演算子でリストに要素が含まれているかを判定する
        return True
    else:
        return False

s = input("組み込み関数かどうかを判定する文字列を入力してください:")

if is_builtin_function(s):
    print(s + "は組み込み関数です")
else:
    print(s + "は組み込み関数ではありません")
組み込み関数かどうかを判定する文字列を入力してください:hello
helloは組み込み関数ではありません

組み込み関数かどうかを判定する文字列を入力してください:zip
zipは組み込み関数です

ソースコードの確認

C言語で実装されている組み込み関数は下記のgitのbltinmodule.cの中を探すと確認できます。

https://github.com/python/cpython/blob/main/Python/bltinmodule.c

printはbltinmodule.c中でbuiltin_printと検索すると確認できます。

importしたソースコードの確認

inspect.getsourceでimportしたモジュールのソースコードの確認は可能です。

import inspect
src = inspect.getsource(inspect.getmodule(inspect)) #inspectモジュールのソースコードを取得
print(src)  #ソースコードを表示

print(inspect.getsource(inspect.getmodule(inspect))) #1行で書く

import os
#osモジュールのソースコードを表示する
print(inspect.getsource(os))

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です