[Tutor] Import module function using variable

Slater, Joseph C. joseph.slater at wright.edu
Wed Jun 13 09:13:30 EDT 2018



> On Jun 13, 2018, at 3:37 AM, Peter Otten <__peter__ at web.de> wrote:
> 
> Slater, Joseph C. wrote:
> 
>> Dear friends,
>> 
>> I am trying to import a function in a module by variable name. The
>> specific example is that my function allows the user to select which
>> function my code will use (in this case, which optimizer in scipy). There
>> is a default for a named variable. I have thing working in a quite unclean
>> way- I import them all and then look them up in globals. I'm not trying to
>> clean it up.
>> 
>> Essentially I'd like to
>> 
>> method = 'newton_krylov'
>> 
>> chosen_optimize_func = (from scipy.optimize import method)
>> 
>> Of course, even I know this shouldn't work. What I tried is
>> 
>> solver_method = __import__('scipy.optimize.' + method, fromlist=[''])
>> 
>> which yields:
>> 
> ---------------------------------------------------------------------------
>> ModuleNotFoundError
>>                       Traceback (most recent call last)
>> 
>> <ipython-input-28-f58650552981> in <module>()
>> ----> 1 solver_method = __import__('scipy.optimize.' + method,
>> fromlist=[''])
>> 
>> 
>> 
>> ModuleNotFoundError
>> : No module named 'scipy.optimize.newton_krylov'
>> 
>> 
>> Well, no, it's not a module but a function.
> 
> Indeed, the function is a name in a module, or an attribute of the module 
> object. You need two steps to access it. First import the module, then use 
> getattr() to extract the function, preferrably
> 
>>>> import scipy.optimize
>>>> method = 'newton_krylov'
>>>> chosen_optimize_func = getattr(scipy.optimize, method)
>>>> chosen_optimize_func
> <function newton_krylov at 0x7f0d0c270bf8>
> 
> but if the module varies, too, use import_module():
> 
>>>> import importlib
>>>> getattr(importlib.import_module("scipy.optimize"), "newton_krylov")
> <function newton_krylov at 0x7f0d0c270bf8>

4 years of Python with 4 packages on pypi and getattr was unknown to me. Thank you for your graciousness. This should have been quite trivial to obtain. 

FWIW: no prompting for this code. It wouldn't make sense. However, I do, at some point, need to include checking to ensure that users provide a response that is an available one. So far, this seems to be necessary as the default has been so consistently the best choice as to beg the question why I even offer another choice. 

Best Regards- Joe



https://people.wright.edu/joseph.slater



More information about the Tutor mailing list