Let's say that I want to implement my custom list
class, and I want to override __getitem__
so that the item
parameter can be initialized with a default None
, and behave accordingly:
class CustomList(list):
def __init__(self, iterable, default_index):
self.default_index = default_index
super().__init__(iterable)
def __getitem__(self, item=None):
if item is None:
item = self._default_index
return super().__getitem__(item)
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
my_list = CustomList(iterable, 2)
This allows for my_list[None]
, but it would be awesome to have something like my_list[]
inherently use the default argument.
Unfortunately that raises SyntaxError
, so I'm assuming that the statement is illegal at the grammar level...my question is: why? Would it conflict with some other statements?
I'm very curious about this, so thanks a bunch to anyone willing to explain!
CodePudding user response:
Its not syntactically useful. There isn't a useful way to programatically use my_list[]
without literally hard-coding it as such. A single piece of code can't sometimes have a variable in the list reference and other times not. In that case, why not just have a different property that gets the default?
@property
def default(self):
return super().__getitem__(self.default)
@property.setter
def default(self, val):
super().__setitem__(self.default, val)
object.__getitem__(self, val)
is defined to have a required positional argument. Python is dynamic and so you can get away with changing that call signature, but that doesn't change how all the other code uses it.
All python operators have a magic method behind them and its always the case that the magic method could expose more features than the operator. Why not let
have a default? So, a = b
would be legal. Once again, that would not be syntactically useful - you could just expose a function if you want to do that.
CodePudding user response:
__getitem__
always takes exactly one argument. You can kindof pass multiple arguments, but this actually just converts it into a tuple:
>>> a = []
>>> a[1, 2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not tuple
Note the "not tuple" in the error message.