How use dynamic function name in import function?

My following code:

listfunctionnames = ('aaa', 'bbb', 'ccc')
for functionname in listfunctionnames:
    from functionname import functionname 

It gives the following error for the command ‘from functionname import functionname’:

ModuleNotFoundError: No module named 'functionname'

What to do now?

from module import aaa, bbb, ccc

If the function names are genuinely dynamic, and not known until runtime:

import module
funcname = some_string.lower()  # For example.
globals()[funcname] = getattr(module, funcname)

That’s not very dynamic :slight_smile: Granted, Pejamide’s example has a literal
list of strings as the function names, but I imagine a more real world
case would receive that list from elsewhere.

Pejamide’s other threads suggest they’re conflating the names of
files/modules with the names of the functions defined inside them.
Possibly they have some Java background or something.

The immediate problem with Pejamide’s code:

 listfunctionnames = ('aaa', 'bbb', 'ccc')
 for functionname in listfunctionnames:
     from functionname import functionname

is that in the import statement the module name is a literal value,
not a variable name, and so are the names being imports. So the line:

 from functionname import functionname

genuinely tries to import from a module named functionname and also to
import the name functionname from that module. Neither of those are
variable names specifying a module or name-from-a-module.

Pejamide’s other thread seems to have a bunch of modules named eg fn3
containing a definition for an fn3() function, so their import pattern
looks like:

 from fn3 import fn3

hence the import inside the for-loop above.

Pejamide: in order to genuinely import dynamic names from a dynamicly
named module you need to use the importlib module, which contains the
machinery used by the import statement. The import statement itself
is very rigid.

I have a question: why are you defining individual functions in
modules of the same name? We don’t normally do that in small programmes.

Cheers,
Cameron Simpson cs@cskk.id.au

My web system uses the menu code per request (for example, ‘Sitemap’). It is internally converted to the function name (here ‘webstxmap’). In this case the converted function name (here ‘webstxmap’ in the file ‘webstxmap.py’) must then imported for execution. Hence the dynamic function name.
Now I am wondering, what instructions can be encoded to execute a function.