Is it possible to redefine which object the brackets [] use?
I can subclass the list
object, but how to I make the interpreter use my subclass in place of the buildin list object? Is it possible?
(I'm pretty 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 don't have a practical use for this- just curious.
Try running the code after you've run the code you posted
Now, determine the type using the code I've posted
it seems that
[]
createslist
, instead ofmlist
, it looks strange :SUpdate
I checked the bytecode generated using
dis
, and the code below was generatedIt appears that
list
will invoke whatever is assigned to it, while[]
will be converted toBUILD_LIST
bytecode. It appears that[]
is not translated tolist
, hence[]
's behavior is stucked to creating list.Update 2
Python class can be updated
Well, except for builtin classes, like list
You can replace list with mlist by using not, as you tried,
but simply
(You might have problems running this in the interpreter, because mlist() calls list() and so on recursively. But if you put the code that defines mlist in a different scope, such as in a module you import, then it will work.) Then you can create a new mlist by
but interestingly, not by
which I had thought was syntactically equivalent. Apparently [ ] is hardcoded to call the built-in list type, rather than whatever object is currently named "list".
The brackets are part of the language. They're used to create lists. It's not possible to redefine that (and not desirable either!).
It's possible. Most things are possible in software, if you're willing to get sufficiently dirty. :) It's a bad idea, of course. If you wrote any software using such a change, it would have a number of problems:
Here's a CPython extension module from 2003 (and example) which works with Python 2.3. It very likely needs to be updated to work with more recent versions of Python, but it demonstrates how dirty you need to get for this particular approach.
Another approach is to change things at the level of the grammar. Logix provides tools for this approach. This involves less C hacking, but brings in an entire new parser and compiler.