python - 一py文件中的中关于import的疑问?
高洛峰
高洛峰 2017-04-18 09:33:31
0
2
940

描述问题

地址见: autojump-中的import (第86-90行)

摘录部分如下(line: 86-90)

import copy as _copy
import os as _os
import re as _re
import sys as _sys
import textwrap as _textwrap

from gettext import gettext as _

为什么要将系统包重命名那样,不是多此一举么?

我的理解, 作为Python开发者,一般来说:

  1. Python官方包也不算多

  2. 浸淫久了,自然耳濡目染耳熟能详,一般不会去重名(虽然理论上会)

  3. 用Python久了,导入哪个官方包,脑袋就会如同肌肉记忆一样

上下文环境

  1. Linux

  2. autojump

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
Peter_Zhu

Here are the answers:

Why are modules imported as _<name> in another module?

To give a simple example, say there are modules a and b, where

# a.py
import os as _os
# import os

def cur_cwd():
    print _os.getcwd()

In addition, the module b.py in the same directory is as follows:

from a import * 
cur_cwd()
# print _os.getcwd()

You cannot use os or _os in b. If os is introduced directly in a.py, then os can be used in b.py.

伊谢尔伦
  • Generally speaking, it is indeed a bit unnecessary, but there may be cases where the names of user-defined packages, classes, or functions are the same as those of the standard library, but developers generally avoid this.

  • One possibility is to hide the content of this code import from the files that reference this code. For example, if there is a main.py that imports this file, these standard library functions cannot be directly called in main.py, such as copy. copy() cannot be used directly, and it may be necessary to do so.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!