Johann Cohen-Tanugi wrote: > On 10/20/2010 11:10 PM, Robert Kern wrote: > >> On Wed, Oct 20, 2010 at 15:58, Johann Cohen-Tanugi<co...@lpta.in2p3.fr> >> wrote: >> >> >>> On 10/20/2010 10:35 PM, Nathaniel Smith wrote: >>> >>> >> >> >>>> IMPORTANT USAGE NOTE: never do this :-) >>>> >>>> >>>> >>> What would you recommand? I do encounter situations where I need >>> instantiation based on the name of the thing to instantiate, typically >>> passed as an argument by the client code/user..... >>> >>> >> Example? >> >> >> > Hi Robert, > so in a big data analysis framework, that is essentially written in C++, > exposed to python with SWIG, plus dedicated python modules, the user > performs an analysis choosing some given modules by name,as in : > myOpt="foo" > my_analyse.perform(use_optimizer=myOpt) > > The attribute use_optimizer is then checked to perform the right > calls/instantiations of python but also C++ objects..... and the actual > crunching number is in the C++ part. > But then I realize that I need to tweak this optimizer's state, and the > optimizer object is accessible from a library pyOpt that has been > swigified from a C++ library. > Then I access the object by calling optObject = > eval("pyOpt.%s(some_args)"%myOpt) > where myOpt would be "foo" in this particular analysis. This is because > what the attribute use_optimizer expects is also the object name in the > library, of course. > It goes without saying that I could do : > if myOpt=="foo": > optObject=pyOpt.foo(some_args) > else: > .... > and if you guys tell me it is way safer, I will do that instead of the > use of eval that I liked because of the compactness..... >
In this case getattr fits... in general, in cases where one could do if action == 'a': a() elif action == 'b': b() the nice (proper?) way of doing it is usually to populate a dictionary: actions['a'] = a actions['b'] = b # automatically populate etc... actions[action]() And on the subject of passing strings around and eval-ing them: http://cache.gawkerassets.com/assets/images/4/2010/03/for_traffic_cameras.jpg Dag Sverre _______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion