An "Object" class?

Gregory Ewing greg.ewing at canterbury.ac.nz
Fri Aug 30 03:42:52 EDT 2019


Cristian Cocos wrote:

>>>>type(print)
> 
> <class 'builtin_function_or_method'>
> 
>>>>isinstance(print, builtin_function_or_method)
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'builtin_function_or_method' is not defined
> 
> Just curious why builtin_function_or_method doesn't work as an argument of
> isinstance().

Because the type object in question is not bound to the name
'builtin_function_or_method' in the builtin namespace. There
is a way to get at it, though:

 >>> import types
 >>> types.BuiltinFunctionType
<class 'builtin_function_or_method'>
 >>> isinstance(print, types.BuiltinFunctionType)
True

When it comes to objects that form part of the interpreter's
internal machinery, the names shown when you print their types
are often just suggestive and aren't meant to be taken literally.
Most of them are available in the 'types' module, however,
possibly under different names. The reasons for all this are
buried in a lot of messy history.

> The bottom line is that I am trying to figure out where exactly the world
> of Python types _diverges from_ what I would expect as a mathematician. It
> makes it easier for me to learn Python this way.

I'm not sure that focusing on classes as mathematical sets is all
that useful. In Python, what class an object belongs to isn't
usually very important. Much more relevant is how the object
*behaves*. We call this "duck typing" -- if it walks like a duck
and quacks like a duck then it might as well be a duck, even if
it doesn't belong to a class called "Duck".

This is why Python doesn't have e.g. an elaborate tower of
numeric types as is seen in some other languages. It just isn't
necessary for getting things done, and Python, being a very
pragmatic language, is all about getting things done.

-- 
Greg



More information about the Python-list mailing list