Overriding Pythons Native Data Types

Is it possible to override which bracket object [] to use?

I can subclass the object list, but how do I get the interpreter to use my subclass instead of the buildin list object? Is it possible?

(I'm sure I'm using the wrong terms for the question - feel free to edit)

>>> class mlist(list):
...     def __init__(self):
...         list.__init__(self)
...     def __getitem__(self, item):
...         return list.__getitem__(self, item) * 2
... 
>>> testlist = mlist()
>>> testlist.append(21)
>>> testlist[0]
42
>>> list = mlist() # maybe setting the 'list' type will do it?
>>> testlist = []
>>> testlist.append(21)
>>> testlist[0]
21                 # Nope
>>> 

I have no practical use for this - just curious.

+3
source share
4 answers

Try to run the code after running the code that you sent

>>> testlist = list()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'mlist' object is not callable

Now determine the type using the code I posted

>>> type([])
<type 'list'>
>>> type(list)
<class '__main__.mlist'>
>>> type(testlist)
<type 'list'>

It seems that it []creates list, and not mlist, it looks strange: S

Update

-, dis,

>>> import dis # python disassembler

>>> def code1():
...     return []
...
>>> dis.dis(code1)
  2           0 BUILD_LIST               0
              3 RETURN_VALUE

>>> def code2():
...     return list()
...
>>> dis.dis(code2)
  2           0 LOAD_GLOBAL              0 (list)
              3 CALL_FUNCTION            0
              6 RETURN_VALUE

, list , , [] BUILD_LIST -. , [] list, [] .

2

Python

>>> class NewList(list):
...     pass
...
>>> a = NewList()
>>> a.append(23)
>>> a[0]
23
>>> def double_getitem(self, key):
...     return list.__getitem__(self, key) * 2
...
>>> NewList.__getitem__ = double_getitem
>>> a[0]
46

, , list

>>> list.__getitem__ = double_getitem
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'list'
+2

. . ( !).

+7

mlist, , ,

list = mlist()

list = mlist

( , mlist() .. . , mlist , , , .) mlist

testlist = list()

,

testlist = []

, , . -, [] , , "".

0

. , .:) , . - , :

  • . , Python, , , [], oops nope .
  • ( , , ), - , . , [] , .
  • , , . , , , , mlist - , , , .

Here's the CPython extension module from 2003 ( and an example ) that works with Python 2.3. Most likely, it should be updated to work with later versions of Python, but it demonstrates how dirty you need this approach.

Another approach is to change things at the grammar level. Logix provides tools for this approach. This is due to a smaller C hack, but contains a whole new parser and compiler.

0
source

All Articles