Dynamic function execution
John Machin
sjmachin at lexicon.net
Sat Nov 25 20:51:22 EST 2006
Cameron Laird wrote:
> In article <mailman.718.1164469686.32031.python-list at python.org>,
> Fredrik Lundh <fredrik at pythonware.com> wrote:
> >Andy Wu wrote:
> >
> >> def func(seconds = None, minutes = None, hours = None):
> >> ...
> >>
> >> In my program I can get a string object('seconds', 'minutes', 'hours')
> >> to specify which parameter to use, the problem is I don't know how to
> >> call the function.
> >>
> >> Say I have a string 'minutes' and a integer 30, now I need to call the
> >> func this way: func(minutes = 30), how do I do this?
> >
> > func(**{"minutes": 30})
> >
> ></F>
> >
>
> Now I'm confused: what's the advantage of
>
> def func(seconds = None, minutes = None, hours = None):
> print seconds
> print minutes
> print hours
>
> func(**{"minutes": 30})
>
> over
>
> def func(seconds = None, minutes = None, hours = None):
> print seconds
> print minutes
> print hours
>
> func(minutes = 30)
>
> ? Or am I missing the point that a better example of what
> Mr. Wu really wants is
>
> def func(seconds = None, minutes = None, hours = None):
> print seconds
> print minutes
> print hours
>
> dimension = "minutes"
> func(**{dimension: 30})
>
> ?
Hi Cameron,
You're on the right track. A better example would have the last two
lines replaced by:
# Simulate obtaining data
argument_name = "minutes"
argument_value = 30
# Then ...
func(**{argument_name: argument_value})
:-)
Cheers,
John
More information about the Python-list
mailing list