0

I have a directory structure like this,

Assignments

├── Assignment1

│ ├── Assignment-1.pdf

│ └── assignment1.py

└── Methods

├── init.py

├── primality.py

I want to import functions from the primality.py file into the assignment1.py file.

What is my relative and absolute import line for this dirctory structure?

I also tried using this, from ..Methods.primality import func

but it gives me an error,

ImportError: attempted relative import with no known parent package

Can anyone explain me what am I doing wrong here?

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
  • 1
    How did you run which file to get that ImportError? – Mr_and_Mrs_D Jan 13 '23 at 14:08
  • There are multiple assignments folders which contains assignment.py file and every assignment.py required different custom packages from the directory Methods. So, in assignment.py file, I import custom packages from the Methods directory with this line "from ..Methods.primality import func" but it resulted into the import error mentioned in the question. – Purvesh Patel Jan 13 '23 at 22:22
  • Yes I asked how do you run this code - what is the command line (for one of the assignments) – Mr_and_Mrs_D Jan 14 '23 at 14:26
  • I ran `$ python3 assignment1.py` – Purvesh Patel Jan 14 '23 at 23:42
  • Does this answer your question? [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – Brian61354270 Jan 15 '23 at 00:31

1 Answers1

0

You should add the missing __init__.py as in:

├── Assignment1

│       ├── Assignment-1.pdf

│       ├── __init__.py # this

│       └── assignment1.py

└── Methods

│       ├── __init__.py

│       ├── primality.py

then go to the Assignments folder and from there run:

$ python3 -m Assignment1.assignment1 # note no py

Then python sees the directory structure as a package structure and Methods/Assignment1 are packages (and you should rename them to methods/assignment1)

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361