12

I am attempting to grade some python submissions that are in separate folders for each student. To do this, there is a function, say f() which I want to run. I understand that if my current path is the same as the one where the file is located, I can simply do

import filename
filename.f()

However, are there better ways? For instance, let's say the directory structure is as follows:

main.py
student/run_this.py

I know that if there is a "__init__.py" file in the student folder, I can just type

import student.run_this

However, without that file, it doesn't work.

Some similar questions I found were

but none of these gave particularly satisfying answers.

Community
  • 1
  • 1
Viknesh
  • 505
  • 1
  • 4
  • 14
  • So what exactly is your issue with the `__init__.py` file? – eazar001 Mar 05 '13 at 11:57
  • 1
    You add the `student` folder to your path, then import `run_this`. That's what the other answers tell you to do, what did you try that didn't work? – Martijn Pieters Mar 05 '13 at 12:05
  • 1
    It's not that it didn't work as much as it didn't seem elegant. Or at least, adding \__init__.py's seems pretty offputting to me - it seems immoral to modify the file structure to access subfolders. For changing the path, I read that was bad practice, but it does seem like a reasonable solution. – Viknesh Mar 05 '13 at 15:43

1 Answers1

11

create an __init__.py module inside the folder student which should contain

from . import *

You can then call any modules from student folder to its parent folder modules as

import student.module.py

If you post any other errors you are facing, we can help further.

dash
  • 89,546
  • 4
  • 51
  • 71
Mathan Kumar
  • 634
  • 2
  • 7
  • 19
  • 1
    Do you think you could explain (or link me to material) explaining why \__init__.py's are required? That did end up working, but I'm a bit confused about what the design logic is – Viknesh Mar 05 '13 at 15:48
  • \_\_init__.py is just as simple as class inheritance logic in c++ or python. When the python looks at a folder it does not includes all the modules available in it. If u specify the functions to be done when python enter into a class at \_\_init__ function, it understands well. here we are just importing the necessary or all modules when python encounters a folder using \_\_init__. – Mathan Kumar Mar 08 '13 at 06:20
  • This answer is the only one that I could find to answer the problem that I had, thanks @MathanKumar ! – George Willcox Dec 03 '16 at 14:20