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> _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor