Dynamic functionname for import_module object

I want to use a dynamic function name for import_module object. Example:
I have three files in the same map: Test1, Function1 and Function2.

Test1 file:
#— Initialize data —
import importlib
import os
import sys
#— Get specified function —
function_name = input('Enter your function name to be processed: ')
#— Check specified function -on existence —
function_file = function_name + ‘.py’
if os.path.isfile(function_file):
#— Import specified function —
module_object = importlib.import_module(function_name)
#— Call specified function —
message = ‘’ + module_object.Function1() + '
message = ‘Your request function ‘’
+ function_file
+ ‘’ does not existed!’

Function1 file:
def Function1():
return ‘Function ‘Function1’ has been processed.’

Function2 file:
def Function2():
return ‘Function ‘Function2’ has been processed.’

That sample procedure does indeed percfectly work. Now I want to modify the next line:
message = ‘’ + module_object.function_name() + '
but I got the attributeError: module ‘Function1’ has no attribute ‘function_name’.
What is your solution for this example?

Next time, please format your code examples as explained here:

About your problem: the code tries to access the function function_name in the module object, which is not what you want. function_name is a string, so you want to retrieve an attribute, the name of which you have as a string. Therefore, you need getattr(module_object, function_name)(). See the documentation for getattr:


$ python3.8
Python 3.8.2+ (heads/3.8:3e72de9e08, Apr 16 2020, 12:25:15) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> my_desired_attr = "match"
>>> re.my_desired_attr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 're' has no attribute 'my_desired_attr'
>>> getattr(re, my_desired_attr)
<function match at 0x7f357ce70ee0>
>>> getattr(re, my_desired_attr)("pattern", "pattern in string")
<re.Match object; span=(0, 7), match='pattern'>