3nondatur
3nondatur

Reputation: 475

How to import a module from a package in Python

I'm quite new to Python und programming in general and have a bit of a problem with packages.

I made a directory called Package_Test and created a file named Test package in it called FUNCTIONS.

This package contains the init file and a file add. add contains a function, also called add that returns the sum of two given numbers.

The directory tree looks as follows:

Package_Test

Test

FUNCTIONS

init

add

I want to use the add function from the package in the file Test and tried the code below, but always get the error

Traceback (most recent call last): File "D:/CLRS_Codes/PACKAGE_TEST/Test.py", line 1, in import FUNCTIONS File "D:\CLRS_Codes\PACKAGE_TEST\FUNCTIONS__init__.py", line 2, in from add import add ModuleNotFoundError: No module named 'add'

In the add file I wrote:

def add(x, y):

    return x + y

In the init file I wrote:

from add import add

In the Test-file I wrote:

import FUNCTIONS

print(add(4,2))

I attached a picture to make the whole thing clearer.

I would be deeply thankful for any help.

The Test-file

Upvotes: 1

Views: 95

Answers (2)

RichAspden
RichAspden

Reputation: 76

First off, empty the __init__.py file.

Then in the Test.py change "import FUNCTIONS" to either:

  1. import FUNCTIONS.add
    • This'll mean you need to call any function from that file as "FUNCTIONS.add.function_name(arguments)"
    • eg the add function in your example will be called through "FUNCTIONS.add.add(number1, number2)"
  2. from FUNCTIONS.add import *
    • This'll allow you to call any functions from that file as "function_name(arguments)
    • eg the add function in your example will be called through "add(number1, number2)"

Upvotes: 1

Joshua Vega
Joshua Vega

Reputation: 599

You can use import FUNCTIONS.add.add as add or from FUNCTIONS.add import add. Both of these methods allow you to reference the add function by it's full name each time.

Upvotes: 3

Related Questions