LoginSignup
5
5

More than 5 years have passed since last update.

グローバル定義(globals)からビルトイン関数(標準組込み関数)を調べる

Last updated at Posted at 2015-02-15

まずは、pythonインタープリタを起動。
Windowsの場合は スタートメニューから IDLE (Python GUI) もしくは Python (command line) を起動。ただし、事前にPythonのインストールが必要です。

LinuxとMacOSの場合(Windowsでも環境変数PATHを設定してあれば同様)
/home/user$ python
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>

globals()でグローバル定義を見てみます。

>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}

dir()でグローバル定義名だけを見ることもできます。

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']

globalsとは何なのかヘルプを見てみます。

>>> help(globals)
Help on built-in function globals in module __builtin__:

globals(...)
    globals() -> dictionary

    Return the dictionary containing the current scope's global variables.

globals__builtin__モジュールに含まれている組み込み関数で、カレントスコープ(現在参照できる範囲)のグローバル変数を含む辞書を返すようです。

__builtins__定義を見てみます。

>>> __builtins__
<module '__builtin__' (built-in)>

>>> type(__builtins__)
<type 'module'>

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

>>> help(__builtins__)
Help on built-in module __builtin__:

NAME
    __builtin__ - Built-in functions, exceptions, and other objects.

FILE
    (built-in)

DESCRIPTION
    Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.

CLASSES
    object
        basestring
            str
            unicode
        buffer
        bytearray
        classmethod
        complex
        dict
        enumerate
        file
        float
        frozenset
        int
            bool
        list
        long
        memoryview
        property
        reversed
        set
        slice
        staticmethod
        super
        tuple
        type
        xrange

    class basestring(object)
     |  Type basestring cannot be instantiated; it is the base for str and unicode.
(長いので割愛)

グローバル関数一覧や例外定義などを知ることができました。

その中のひとつ、zipは何をするものか見てみます。

>>> zip
<built-in function zip>

>>> type(zip)
<type 'builtin_function_or_method'>

>>> dir(zip)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

>>> help(zip)
Help on built-in function zip in module __builtin__:

zip(...)
    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is truncated
    in length to the length of the shortest argument sequence.

与えたシーケンスデータの各i番目の要素をタプルにしたものをリストにしてくれるようです。
使ってみましょう。

>>> zip((1, 2, 3), [True, False, None], "ABC")
[(1, True, 'A'), (2, False, 'B'), (3, None, 'C')]

最初の要素を集めたタプル、2番目の要素を集めたタプル、3番目の要素を集めたタプルのリストが表示されました。

__builtins__はモジュールのようですが、__builtins__を別の定義に変えてしまったらどうなるでしょうか?
ちょっといたずらしてみます。

>>> __builtins__ = None
>>> __builtins__
>>> globals()

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    globals()
NameError: name 'globals' is not defined

>>> dir()

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    dir()
NameError: name 'dir' is not defined
>>> 

あらら。ビルトイン関数が使えなくなってしまいました。
何か関数を呼び出そうとしたとき、Pythonインタープリタはローカル定義(locals())やグローバル定義(globals())に関数定義がないか調べ、なければ更にグローバル定義の__builtins__にビルトイン関数定義がないか調べて、関数を呼び出してくれているようです。

なお、使えなくなったビルトイン関数は、__builtins__ を削除(del)することで再定義されるようです。

>>> del __builtins__
>>> globals()
{'__builtins__': {'bytearray': <type 'bytearray'>, 'IndexError': <type 'exceptions.IndexError'>, 'all': <built-in function all>, 'help': Type help() for interactive help, or help(object) for help about object., 'vars': <built-in function vars>, 'SyntaxError': <type 'exceptions.SyntaxError'>, 'unicode': <type 'unicode'>, 'UnicodeDecodeError': <type 'exceptions.UnicodeDecodeError'>, 'memoryview': <type 'memoryview'>, 'isinstance': <built-in function isinstance>, 'copyright': Copyright (c) 2001-2014 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
(長いので割愛)

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']

最初に試した時と表示される内容が変わってしまいましたが、問題なく使えるようです。

ちなみに、グローバル定義にある__name__は、コマンドとして起動されたときには '__main__'が入り、パッケージとしてimportされたときにはパッケージ名が入るグローバル変数です。
Pythonスクリプトで if __name__ == '__main__': という記述を見かけますよね。

>>> __name__
'__main__'
5
5
0

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
5
5