简体   繁体   中英

How to use [] with a custom __builtin__ list?

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM