Home  >  Q&A  >  body text

python - 一py文件中的中关于import的疑问?

描述问题

地址见: 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

高洛峰高洛峰2741 days ago926

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 09:35:31

    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.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:35:31

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

    reply
    0
  • Cancelreply