简体   繁体   中英

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

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.

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)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM