question

Tim Chase python.list at tim.thechases.com
Tue Jan 22 15:31:32 EST 2008


> def albumInfo(theBand):
>     def Rush():
>         return ['Rush', 'Fly By Night', 'Caress of Steel',
'2112', 'A Farewell to Kings', 'Hemispheres']
>
>     def Enchant():
>         return ['A Blueprint of the World', 'Wounded', 'Time Lost']
>
> The only problem with the code above though is that I
> don't know how to call it, especially since if the user is
> entering a string, how would I convert that string into a
> function name? For example, if the user entered 'Rush',
> how would I call the appropriate function -->
> albumInfo(Rush()) >

It looks like you're reaching for a dictionary idiom:

  album_info = {
    'Rush': [
      'Rush',
      'Fly By Night',
      'Caress of Steel',
      '2112',
      'A Farewell to Kings',
      'Hemispheres',
      ],
    'Enchant': [
      'A Blueprint of the World',
      'Wounded',
      'Time Lost',
      ],
    }

You can then reference the bits:

  who = "Rush" #get this from the user?
  print "Albums by %s" % who
  for album_name in album_info[who]:
    print ' *', album_name

This is much more flexible when it comes to adding groups
and albums because you can load the contents of album_info
dynamically from your favorite source (a file, DB, or teh
intarweb) rather than editing & restarting your app every time.

-tkc

PS: to answer your original question, you can use the getattr()
function, such as

  results = getattr(albumInfo, who)()

but that's an ugly solution for the example you gave.







More information about the Python-list mailing list