Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python builtin functions aren't really functions, right?

Tags:

python

Was just thinking about Python's dict "function" and starting to realize that dict isn't really a function at all. For example, if we do dir(dict), we get all sorts of methods that aren't include in the usual namespace of an user defined function. Extending that thought, its similar to dir(list) and dir(len). They aren't function, but really types. But then I'm confused about the documentation page, http://docs.python.org/2/library/functions.html, which clearly says functions. (I guess it should really just says builtin callables)

So what gives? (Starting to seem that making the distinction of classes and functions is trivial)

like image 711
EdgarArout Avatar asked Aug 30 '13 14:08

EdgarArout


2 Answers

It's a callable, as are classes in general. Calling dict() is effectively to call the dict constructor. It is like when you define your own class (C, say) and you call C() to instantiate it.

like image 88
Hammerite Avatar answered Nov 15 '22 21:11

Hammerite


One way that dict is special, compared to, say, sum, is that though both are callable, and both are implemented in C (in cpython, anyway), dict is a type; that is, isinstance(dict, type) == True. This means that you can use dict as the base class for other types, you can write:

class MyDictSubclass(dict):
    pass

but not

class MySumSubclass(sum):
    pass

This can be useful to make classes that behave almost like a builtin object, but with some enhancements. For instance, you can define a subclass of tuple that implements + as vector addition instead of concatenation:

class Vector(tuple):
    def __add__(self, other):
        return Vector(x + y for x, y in zip(self, other))

Which brings up another interesting point. type is also implemented in C. It's also callable. Like dict (and unlike sum) it's an instance of type; isinstance(type, type) == True. Because of this weird, seemingly impossible cycle, type can be used to make new classes of classes, (called metaclasses). You can write:

class MyTypeSubclass(type):
    pass

class MyClass(object):
    __metaclass__ = MyTypeSubclass

or, in Python 3:

class MyClass(metaclass=MyTypeSubclass):
    pass

Which give the interesting result that isinstance(MyClass, MyTypeSubclass) == True. How this is useful is a bit beyond the scope of this answer, though.

like image 25
SingleNegationElimination Avatar answered Nov 15 '22 21:11

SingleNegationElimination