为什么导入整个模块然后重命名其中一个函数?
Why import a whole module then rename one of its functions?
在Flask的顶层__init__.py
中,进行了以下操作:
from . import json
jsonify = json.jsonify
- 为什么不
import json
?
- 为什么重命名
json.jsonify
?为什么不 (i) import json
然后在需要的地方调用 json.jsonify()
或 (ii) from json import jsonify
,然后在需要的地方调用 jsonify()
?
我知道有两条评论,但对我启发不大:
# We're not exposing the actual json module but a convenient wrapper around
# it.
from . import json
# This was the only thing that flask used to export at one point and it had
# a more generic name.
jsonify = json.jsonify
- Why not
import json
?
因为那会从标准库中导入 json
模块,而作者想导入他们自己的 json
模块。
- Why rename
json.jsonify
?
为了让它更容易书写和阅读。假设您正在使用 flask
:flask.jsonify()
比 flask.json.jsonify()
编写起来更快,可读性更好(或者,它更容易导入,并且不会让您觉得自己是从图书馆的深处导入一些东西。
Why not (i) import json
then call json.jsonify()
where needed
请记住,此文件指定 exports。您必须将其称为 flask.json.jsonify()
.
or (ii) from json import jsonify
, then call jsonify()
where needed?
是的,第二行可以写成
from .json import jsonify
(如 mgilson 正确指出)。我想这是个人风格的问题。
在Flask的顶层__init__.py
中,进行了以下操作:
from . import json
jsonify = json.jsonify
- 为什么不
import json
? - 为什么重命名
json.jsonify
?为什么不 (i)import json
然后在需要的地方调用json.jsonify()
或 (ii)from json import jsonify
,然后在需要的地方调用jsonify()
?
我知道有两条评论,但对我启发不大:
# We're not exposing the actual json module but a convenient wrapper around
# it.
from . import json
# This was the only thing that flask used to export at one point and it had
# a more generic name.
jsonify = json.jsonify
- Why not
import json
?
因为那会从标准库中导入 json
模块,而作者想导入他们自己的 json
模块。
- Why rename
json.jsonify
?
为了让它更容易书写和阅读。假设您正在使用 flask
:flask.jsonify()
比 flask.json.jsonify()
编写起来更快,可读性更好(或者,它更容易导入,并且不会让您觉得自己是从图书馆的深处导入一些东西。
Why not (i)
import json
then calljson.jsonify()
where needed
请记住,此文件指定 exports。您必须将其称为 flask.json.jsonify()
.
or (ii)
from json import jsonify
, then calljsonify()
where needed?
是的,第二行可以写成
from .json import jsonify
(如 mgilson 正确指出)。我想这是个人风格的问题。