It is possible to call reverse with arguments for example:
reverse('page', args=['page1'])
finds the url named page that takes an argument.
My question is how would I do this if I am using Python's map? I want something of this form:
map(reverse, ITERABLE)
where iterable is a bunch of of named urls with args. Thus far I have been unsuccessful at doing this.
edit based on comments and开发者_StackOverflow社区 Adam's and rulfzid's answers:
The following iterable is an example that works with both rulfzid's (editing it as my comment suggests) and Adam's answer
iterable = [['page', ['about']], ['home', None]]
My only other question is which would be faster?
You could just use a list comprehension:
[reverse(page, args=args) for page, args in ITERABLE]
Assuming, of course, that ITERABLE is something like [(page, args), (page1, arg1), ...]
Assuming that each item in ITERABLE
is a tuple (or list) consisting of the URL and the arguments, you could use a lambda like so:
map(lambda x: reverse(x[0], args=x[1]), ITERABLE)
It sounds like you need functools.partial
.
from functools import partial
reverse_page = partial(reverse, 'page', None)
map(reverse_page, ITERABLE)
Should do the trick if you need to map:
['page1', 'page2', 'page3']
with no url_conf
and page
as the view.
You can use keyword args with it, but there is no reason to construct dict
s if you don't need to.
It's faster than using lambda
or a list comprehension for non-trivial lengths of iterable
because reverse
and 'page'
only have to be looked up once.
Edit: If you're not actually using one argument over and over again, partial
isn't what you want, just plain map
:
map(reverse, ('page', 'home'), itertools.repeat(None), ('about', None))
or like this:
map(reverse, *zip(('page', None, 'about'), ('home', None, None)))
depending on how the info was organized. No need for a lambda here, lambda is slow.
精彩评论