ModuleNotFoundError: No module named 'A given module in package' when running the code

Question:

Here is the entire code:

MyApp/
            
     * mypkg/
              * __init__.py
              * mod1.py
              * mod2.py
     * Demo.py
      

I am trying to run this app from Demo.py

mod1.py :


class Person:
    def __init__(self,name,age,address):
        self.name = name
        self.age = age
        self.address = address

    def show_person(self):
        return "the name of the person is {0} and age is {1} ".format(self.name,self.age)

    

mod2.py :

import mod1 as P

class Student(P.Person):
    def __init__(self,name,age,address,standard,grade):
        super(Student,self).__init__(name,age,address)
        self.standard = standard
        self.grade = grade

    def show_student(self):
        return "The name of the student is {0} and he is studing in {1} standard".format(self.name,self.standard)

__init__.py:

__all__ = ["mod1","mod2"]

Demo.py :

from mypkg import *

a = Person('John',12,'Near S School')
print(a.show_person())

b = Student('name', 17, 'Near X Resturant',12, 'B')
print(b.show_student())

The output:

Traceback (most recent call last):
  File "d:ROOTWORKPythonMyAppDemo.py", line 1, in <module>
    from mypkg import *
  File "d:ROOTWORKPythonMyAppmypkgmod2.py", line 1, in <module>
    import mod1 as P
ModuleNotFoundError: No module named 'mod1'

The output should be a string with name and standard

Example :

The name of the Student is Jhon and he is studying in standard 10.

Asked By: Satyaki De Sarkar

||

Answers:

In mod2.py, change the import to

import mypkg.mod1 as P

In Demo.py, change the import to

from mypkg.mod1 import Person
from mypkg.mod2 import Student

This should allow you to run the program.

Answered By: Fractalism
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.