[Numpy-discussion] function name as parameter

Johann Cohen-Tanugi cohen@lpta.in2p3...
Thu Oct 21 03:43:56 CDT 2010



On 10/20/2010 11:49 PM, Zachary Pincus wrote:
>> 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.....
>>      
> Well, optObject=getattr(pyOpt, myOpt) is a bit nicer and marginally
> more likely to return sane error messages than optObject=eval("pyOpt.
> %s"%myOpt). Then you could do result=optObject(some_args)...
>
>    
ok I definitely like that better than eval.
> But why not have the user just pass in the relevant optObject from the
> pyOpt namespace (or some restricted namespace that just has the
> relevant functions exposed)? E.g.
> my_analysis.perform(optimizer=pyOpt.Amoeba)
> rather than
> my_analysis.perform(optimizer='Amoeba')
>    
Well, that means that the user now needs to know about the underlying 
C++ library, etc....
Just requiring from the user that he knows the *name* of the optimizer 
was the primary driver.
But I understand that it easily drives to a dead-end.

my_analysis.perform(optimizer=pyOpt.Amoeba)

is definitely allowed in the code as well, and that is what I do after I 
have fiddle with the optimizer object.

Thanks to all for the tips and advices!
Johann
> This lets users do introspection on the pyOpt namespace to see what
> functions they can choose from, which is rather friendlier in an
> interactive environment.
>
> Zach
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>    


More information about the NumPy-Discussion mailing list