[Numpy-discussion] function name as parameter
Johann Cohen-Tanugi
cohen at lpta.in2p3.fr
Wed Oct 20 17:33:36 EDT 2010
On 10/20/2010 11:10 PM, Robert Kern wrote:
> On Wed, Oct 20, 2010 at 15:58, Johann Cohen-Tanugi<cohen at 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.....
As to Nathaniel's last point : yes of course the type changing of 'x' in
my code would be unacceptable if x becomes complicated enough. This was
not meant to be used in *any* situation.
cheers,
Johann
More information about the NumPy-Discussion
mailing list