Examine built-in functions (standard built-in functions) from globals

First, start the python interpreter. For Windows, start ʻIDLE (Python GUI)orPython (command line)` from the start menu. However, you need to install Python in advance.

For Linux and MacOS (even for Windows if the environment variable PATH is set))


/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.
>>>

Let's look at the global definition with globals ().

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

You can also see only the global definition name with dir ().

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

Let's take a look at the help on what globals is.

>>> 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 is a built-in function included in the __ builtin__ module, which seems to return a dictionary containing global variables in the current scope (currently visible range).

Let's take a look at the __builtins__ definition.

>>> __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.
(Omitted because it is long)

I was able to know the list of global functions and exception definitions.

Let's see what one of them, zip, does.

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

It seems that it makes a list of tuples of each i-th element of the given sequence data. Let's use it.

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

A list of tuples with the first element, tuples with the second element, and tuples with the third element is displayed.

__builtins__ seems to be a module, but what if you change__builtins__ to a different definition? I'll play a little prank.

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

Oops. The built-in function is no longer available. When trying to call any function, the Python interpreter looks for a function definition in the local definition (locals ()) or global definition (globals ()), otherwise it has a built-in function definition in the global definition __builtins__. It seems that it is checking for the existence and calling the function.

In addition, the built-in function that can no longer be used seems to be redefined by deleting (del) __builtins__.

>>> 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.
(Omitted because it is long)

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

The displayed content has changed from the first time I tried it, but it seems that it can be used without problems.

By the way, __name__ in the global definition is a global variable that contains '__main__' when it is started as a command and the package name when it is imported as a package. You see the description ʻif name =='main': `in your Python script.

>>> __name__
'__main__'

Recommended Posts

Examine built-in functions (standard built-in functions) from globals
Built-in functions
Python's built-in functions
Python built-in functions ~ Zip ~
Wrap Python built-in functions
Study from Python Hour3: Functions