简体   繁体   中英

Python2: Importing same function from multiple files

I am using Python 2.7 and I am making a simple grader in Python. What this grader does is following:

  1. Iterates over all the folders and imports the folder as a module by adding init .py
  2. Run one of the methods and compare the output to a predefined output
  3. If the output is same then assign True as result else False
  4. Move to the next student and import his/her code again

Now all the students have the same file name 'test.py' and the same function name - let's say add

My ISSUE - It seems like when Python imports from the method from the first student's code, it is being carried the same for other students as well.

Sample Code

## get the output of the function
output = 5

subdirectories = "contains the directory where all student codes are"

# find python files inside each directory
# copy the init file and run the code
c = 0
for student in subdirectories:
    copyfile(src, os.path.join(student,'__init__.py')) # to make the folder a package
    os.chdir(student)

    from test import * # test is the file name

    # this line below evaluates the same function again and again instead of importing the new method from a different student file
    output_student = eval( functionName + '('+functionArguments+')')

Question - How can I import a method with the same name from multiple Python files, each time overwriting the function definition.

I think import_module() will do what you want.

from importlib import import_module
...
module = import_module(<module_to_import>)
output_student = module.functionName(functionArguments)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM