When passing functions as args, how to pass extra args for passed function?

Sean Ross sross at connectmail.carleton.ca
Tue Sep 16 19:17:14 EDT 2003


<python at sarcastic-horse.com> wrote in message
news:mailman.1063746594.3920.python-list at python.org...
> When I pass a function as an arg, like for map(...), how do I pass args to
> use for that function?
>
> If I have a function like this:
>
> def pretty_format(f, fmt='%0.3f'):
>     return fmt % f
>
> I want to use it with map() like this:
>
> formatted = map(pretty_format, unformatted_list)
> #exept I want fmt='%4.5f' !!!
>
> I need to figure out how to pass a non-default value for fmt.  How do I do
> that?
>
>
>


Here's one way:

formatted = map(lambda f: pretty_format(f, fmt='%4.5f'), unformatted_list)


And, here's another (requires itertools, available in Python 2.3 [*]):

from itertools import repeat
formatted = map(pretty_format, unformated_list, repeat('%4.5f'))


[*]
# or you can roll your own,
# credit: http://www.python.org/dev/doc/devel/lib/itertools-functions.html
def repeat(object, times=None):
         if times is None:
             while True:
                 yield object
         else:
             for i in xrange(times):
                 yield object

# may need 'from __future__ import generators' at top of file

HTH
Sean






More information about the Python-list mailing list