Python import and from - How to use functions in outer files or directories in Python

Python import helps the files and directories to be connected or callable. import is used to import the functions or values in the outer file or directory. import is often used with from.

Roughly explaining,

from (box) import (item)

is a basic statement. In the case importing function A in file B,

from B import A

is declared before using function A.


Now let's check the import system in Python to see 2 files, and

Application Structure


from util import helper

helper.greeting()  # Hello

def greeting():
    print('Hello') is in util folder and imports greeting function in that is in the same hierarchy. The above codes works properly.

Incorrect and Correct Codes

Incorrect code

from util import helper

greeting()  # Hello

The above is incorrect because the file only imports helper and doesn't import greeting function. It's true that greeting is in, but the function itself is not called in this case.

Correct code

from util.helper import greeting

greeting()  # Hello

The above code is correct because greeting is called.


Powered by Markdown