Newbie help- Can multiple instances with multiple names automatically created.

Jan Kaliszewski zuo at chopin.edu.pl
Mon Jan 4 23:56:57 CET 2010


2010-01-04, 22:54:41 Chris Rebert <clp2 at rebertia.com> wrote:

> name2drink = {}
> for booze in liquors:
>     for juice in juices:
>         name = juice +" "+booze # or however you're naming them
>         drink = Bottle(booze, juice)
>         name2drink[name] = drink

@Nav: ...and if you really desire to have those objects in global
(module's) namespace, you can do that:

     global_namespace = globals()
     for booze in liquors:
         for juice in juices:
             name = '{0}_with_{1}_juice'.format(booze, juice)
             drink = Bottle(booze, juice)
             global_namespace[name] = drink

     # then you have them in module's namespace
     print(wine_with_apple)
     wine_with_apple.rating = 0.9

Though in most cases it'd be not necessary.

Cheers,
*j

PS. Another way to express practically the same:

     from itertools import product

     globals().update(('{0}_with_{1}_juice'.format(booze, juice),
                       Bottle(booze, juice))
                      for booze, juice in product(liquors, juices))

-- 
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>



More information about the Python-list mailing list