Is `list()` considered a function?

2020-07-10 09:21发布

问题:

list is obviously a built-in type in Python. I saw a comment under this question which calls list() a built-in function. And when we check the documentation, it is, indeed, included in Built-in functions list but the documentation again states:

Rather than being a function, list is actually a mutable sequence type

Which brings me to my question: Is list() considered a function? Can we refer to it as a built-in function?

If we were talking about C++, I'd say we are just calling the constructor, but I am not sure if the term constructor applies to Python (never encountered its use in this context).

回答1:

list is a type, which means it is defined somewhere as a class, just like int and float.

>> type(list)
<class 'type'>

If you check its definition in builtins.py (the actual code is implemented in C):

class list(object):
    """
    Built-in mutable sequence.

    If no argument is given, the constructor creates a new empty list.
    The argument must be an iterable if specified.
    """

    ...

    def __init__(self, seq=()): # known special case of list.__init__
        """
        Built-in mutable sequence.

        If no argument is given, the constructor creates a new empty list.
        The argument must be an iterable if specified.
        # (copied from class doc)
        """
        pass

So, list() is not a function. It is just calling list.__init__() (with some arguments which are irrelevant for this discussion) just like any call to CustomClass() is doing.

Thanks for @jpg for adding in the comments: classes and functions in Python have a common property: they are both considered as callables, which means they are allowed to be invoked with (). There is a built-in function callable that checks if the given argument is callable:

>> callable(1)
False
>> callable(int)
True
>> callable(list)
True
>> callable(callable)
True

callable is also defined in builtins.py:

def callable(i_e_, some_kind_of_function): # real signature unknown; restored from __doc__
    """
    Return whether the object is callable (i.e., some kind of function).

    Note that classes are callable, as are instances of classes with a
    __call__() method.
    """
    pass


回答2:

When you call list(), you're invoking the constructor of the list class (list.__init__).

If you have any doubt about the use of the term "constructor" in Python, this is the exact word that the implementers of list chose to refer to __init__:

https://github.com/python/cpython/blob/master/Objects/listobject.c#L2695