Python import and from - How to use functions in outer files or directories in 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 (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,
/game.py /util -math.py -helper.py
from util import helper helper.greeting() # Hello
def greeting(): print('Hello')
math.py is in
util folder and
greeting function in
helper.py that is in the same hierarchy. The above codes works properly.
Incorrect and Correct Codes
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.
from util.helper import greeting greeting() # Hello
The above code is correct because
greeting is called.