How do you override the result of unpacking syntax *obj
and **obj
?
For example, can you somehow create an object thing
which b
I did succeed in making an object that behaves how I described in my question, but I really had to cheat. So just posting this here for fun, really -
class Thing:
def __init__(self):
self.mode = 'abc'
def __iter__(self):
if self.mode == 'abc':
yield 'a'
yield 'b'
yield 'c'
self.mode = 'def'
else:
yield 'd'
yield 'e'
yield 'f'
self.mode = 'abc'
def __getitem__(self, item):
return 'I am a potato!!'
def keys(self):
return ['hello world']
The iterator protocol is satisfied by a generator object returned from __iter__
(note that a Thing()
instance itself is not an iterator, though it is iterable). The mapping protocol is satisfied by the presence of keys()
and __getitem__
. Yet, in case it wasn't already obvious, you can't call *thing
twice in a row and have it unpack a,b,c
twice in a row - so it's not really overriding splat like it pretends to be doing.