Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand from . import in python? [duplicate]

Tags:

python

flask

I am new to python and flask framework.

for below codes:

from flask import Blueprint
main = Blueprint('main', __name__)
from . import views, errors

I found python has many import ways, for example:

import foo
import foo.bar
from foo import bar
from foo import bar, baz
from foo import *
from foo import bar as fizz

but how to understand from . import ...?

like image 585
pangpang Avatar asked Mar 14 '23 07:03

pangpang


2 Answers

When you use import XXX, you import all the contents of XXX under the namespace XXX, and you have access to them using XXX.abc, XXX.example etc...

When you use from XXX import abc, you only overwrite the variable abc of your globals() dictionnary. The special from XXX import * does the same, but for all variables whose name doesn't begins with an underscore.

Finally, the "as" keyword allows you to give to the imported module/function/variable the name you want.

When you have a module containing some folders, and you want to import from another file, . refers to the directory containing the current file, .. to the directory containing it, and so on.

For a less concise / more precise answer : `from ... import` vs `import .`

like image 181
Labo Avatar answered Mar 16 '23 21:03

Labo


from . import foo, bar

It means import foo, bar from current directory.

from foo import *

means from module foo import all items. But I think this is not a good practice.If you can and need only few items from a module do it like normal import rather than this one. For more info check here.

like image 20
kuskmen Avatar answered Mar 16 '23 21:03

kuskmen