3

I'm trying to understand how __builtin__ works in Python. My code is as follows:

import __builtin__

class MyList(list):
    pass

__builtin__.list = MyList

a = [1,2,3,4,5]
b = list([1,2,3,4,5])

print 'A: ', type(a)
print 'B: ', type(b)

When I print the types of both of the lists, I get:

A:  <type 'list'>
B:  <class '__main__.MyList'>

Why aren't both lists of type MyList and how can I achieve that [] syntax would also be of type MyList?

martineau
  • 119,623
  • 25
  • 170
  • 301
intelis
  • 7,829
  • 14
  • 58
  • 102

1 Answers1

2

If you check how [] is handled by CPython interprerter with dis module, you would see that it spawns BUILD_LIST instruction:

>>> def x():
...     x = [1,2]
... 
>>> dis.dis(x)
  2           0 LOAD_CONST               1 (1)
              3 LOAD_CONST               2 (2)
              6 BUILD_LIST               2
              9 STORE_FAST               0 (x)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE

The corresponding instruction triggers direct call to C function PyList_New (it is handled in ceval.c):

2202        case BUILD_LIST:
2203            x =  PyList_New(oparg);

I think that if CPython would search list constructor in __builtin__ pseudo-module each time [] are used in source, it would be much slower, so this behavior can be considered an optimization.

So what you asking is not achievable in vanilla CPython.

myaut
  • 11,174
  • 2
  • 30
  • 62