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.

Example

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

Application Structure

/game.py
/util
 -math.py
 -helper.py

math.py

from util import helper

helper.greeting()  # Hello

helper.py

def greeting():
    print('Hello')

math.py is in util folder and math.py imports greeting function in helper.py 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 helper.py, 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.

Comments

Powered by Markdown

More