[Python] Asterisk in Python?
Rob Hudson
rob at euglug.net
Fri Jun 9 12:09:49 PDT 2006
I was reading this page about template tags in Django:
http://www.b-list.org/weblog/2006/06/07/django-tips-write-better-template-tags
He has some Python code that I never knew existed. In the last code
sample in the sub-section titled, "Iteration 4: Make and Model" he has
this code:
class LatestContentNode(Node):
def __init__(self, model, num, varname):
self.num, self.varname = num, varname
self.model = get_model(*model.split(‘.’))
def render(self, context):
context[self.varname] =
self.model._default_manager.all()[:self.num]
return ”
In the description, he states:
the asterisk in there is a Python shortcut for saying “take this list of
things and use it as your arguments”
I had this conversation with Python:
>>> l = [1,2]
>>> *l
File "<stdin>", line 1
*l
^
SyntaxError: invalid syntax
>>> def fun(a,b):
... print a
... print b
...
>>> fun(l)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: fun() takes exactly 2 arguments (1 given)
>>> fun(*l)
1
2
Hmmm, that's kind of cool. I never knew that existed.
-Rob
More information about the Python
mailing list