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.

asked Mar 5, 2013 at 11:42
3
  • So what exactly is your issue with the __init__.py file? Commented Mar 5, 2013 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? Commented Mar 5, 2013 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. Commented Mar 5, 2013 at 15:43

1 Answer 1

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
91.8k4 gold badges55 silver badges72 bronze badges
answered Mar 5, 2013 at 12:25
Sign up to request clarification or add additional context in comments.

3 Comments

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
__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__.
This answer is the only one that I could find to answer the problem that I had, thanks @MathanKumar !

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.