Reputation: 475
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.
Upvotes: 1
Views: 95
Reputation: 76
First off, empty the __init__.py file.
Then in the Test.py change "import FUNCTIONS" to either:
Upvotes: 1
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