Aditya
Aditya

Reputation: 1274

ImportError while importing a python package into a python module

I create a python package namely package_demo and it has three python module init.py, employee.py and manager.py.

employee.py:-

def topSalary_employee(salary_list):
    return max(salary_list);

def leastSalary_employee(salary_list):
    return min(salary_list);

def avarageSalary_employee(salary_list):
    summation=0;
    for salary in salary_list:
        summation+=salary;
    return summation;

manager.py:-

def topSalary_manager(salary_list):
    return max(salary_list);

def leastSalary_manager(salary_list):
    return min(salary_list);

def avarageSalary_manager(salary_list):
    summation=0;
    for salary in salary_list:
        summation+=salary;
    return summation;

init.py:-

from manager import*;
from employee import*;

Now I want to access all function of the manager.py and employee.py into another python module namely AAA.py which is resided outside the package package_demo.Here is the code for AAA.py

AAA.py:-

import package_demo

employee_salary_list = [12000,23000,18000,25000,8000,17000];
manager_salary_list = [32000,45000,28000,50000,38000,44000];

print("\t...Manager Salary Details...");
print("Highest salary of Manager : ",package_demo.topSalary_employee(manager_salary_list));
print("Lowest salary of Manager : ",package_demo.leastSalary_manager(manager_salary_list));
print("Average salary of Manager : ",package_demo.avarageSalary_manager(manager_salary_list));

print("\t...Employee Salary Details...");
print("Highest salary of Employee : ",package_demo.topSalary_employee(employee_salary_list));
print("Lowest salary of Employee : ",package_demo.leastSalary_employee(employee_salary_list));
print("Average salary of Employee : ",package_demo.avarageSalary_employee(employee_salary_list));

But when I run AAA.py program,it will show some error likes below

Traceback (most recent call last):
  File "F:\Document\Files\Coding\Java Eclipse\Python Project\First Project\src\AAA.py", line 1, in <module>
    import package_demo
  File "F:\Document\Files\Coding\Java Eclipse\Python Project\First Project\src\package_demo\__init__.py", line 1, in <module>
    from manager import*;
ImportError: No module named 'manager'

Upvotes: 0

Views: 152

Answers (1)

Raniz
Raniz

Reputation: 11113

All imports are evaluated from the directory you start Python in, so when init.py is trying to import manager Python will try to look from the directory you're currently in and not from the directory where init.py resides.

You wan to either use relative imports or convert your import to an absolute import:

Relative:

from .manager import*;
from .employee import*;

Absolute:

from package_demo.manager import*;
from package_demo.employee import*;

Upvotes: 3

Related Questions