Today I'm learning using *
and **
to unpack arguments.
I find that both list
, str
, tuple
, dict
can be unpacked by *
.
I guess because they are all iterables. So I made my own class.
# FILE CONTENT
def print_args(*args):
for i in args:
print i
class MyIterator(object):
count = 0
def __iter__(self):
while self.count < 5:
yield self.count
self.count += 1
self.count = 0
my_iterator = MyIterator()
# INTERPRETOR TEST
In [1]: print_args(*my_iterator)
0
1
2
3
4
It works! But how to make a mapping
object like dict
in python so that **
unpacking works on it? Is it possible to do that? And is there already another kind of mapping
object in python except dict
?
PS:
I know I can make an object inherit from dict
class to make it a mapping object. But is there some key magic_method
like __iter__
to make a mapping object without class inheritance?
PS2:
With the help of @mgilson's answer, I've made an object which can be unpacked by **
without inherit from current mapping object:
# FILE CONTENT
def print_kwargs(**kwargs):
for i, j in kwargs.items():
print i, '\t', j
class MyMapping(object):
def __getitem__(self, key):
if int(key) in range(5):
return "Mapping and unpacking!"
def keys(self):
return map(str, range(5))
my_mapping = MyMapping()
print_kwargs(**my_mapping)
# RESULTS
1 Mapping and unpacking!
0 Mapping and unpacking!
3 Mapping and unpacking!
2 Mapping and unpacking!
4 Mapping and unpacking!
Be aware, when unpacking using **
, the key in your mapping object should be type str
, or TypeError will be raised.