4

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 ...?

pangpang
  • 8,581
  • 11
  • 60
  • 96

2 Answers2

5

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 .`

Community
  • 1
  • 1
Labo
  • 2,482
  • 2
  • 18
  • 38
2
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.

kuskmen
  • 3,648
  • 4
  • 27
  • 54