IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> 【代码规范化】如何正确的使用 Python Import -> 正文阅读

[Python知识库]【代码规范化】如何正确的使用 Python Import

from ... import vs. import

Always avoid wildcard imports like such:

from my_module import *  # don't use this

Instead, use regular import like:

import my_module  # use this

Why?

  • using wildcard import will pollute namespaces
  • Using wildcard import will not import names with a leading underscore (unless the module defines an __all__ list)
  • PEP8 recommend using regular import

What does __init__.py do?

  1. __init__.py is used to specify a package, when import is trying to find the modules,
    But it is not required: meaning a package without __init__.py,
    The system can still find the modules after configuring appropriate PYTHONPATH using
    sys.path.append.

  2. __init__.py is executed after importing the package, I’ve seen
    sub-directory being imported by appending as environment variable within __init__.py

Example:

so instead of using import project.foo.bar for the following structure:

project/
    __init__.py
    foo/
        __init__.py
        bar/
            b.py

inside the __init__.py, we could do a sys.path.append(PATH_TO_BAR)

so with this file structure, you can just do import project

they could even add the import statement for you in the __init__.py, although it is not transparent.

project/
    __init__.py
    foo/
        bar/
            b.py

Note: Whatever gets appended last overrides the previous
env variable, so import to the same name module will find the latest append

Dot notation (.) in Import

parent/
    __init__.py
    file.py
    one/
        __init__.py
        anotherfile.py
    two/
        __init__.py
    three/
        __init__.py

Each dot in your import will refer to something inside the package, could be another package
or a module. But it can’t be a class.

Import python modules could look like:
import parent.file or import parent.one.anotherfile

From … import classes or functions look like this:
from parent.file import class
which gives you direct access to the class namespace, but not the example above.

Import Order

Based on PEP8, imports should be grouped by the following order:

  1. Standard library import
  2. Related third-party import
  3. Local application/library specific import

What is Standard Library Imports?

Standard library are installed automatically by Python installer, full documentation link
is here: https://docs.python.org/3/library/

What is the order after grouping?

There is no specific rules, but based on common preferences, use alphabetical order, with
import first and from … import after

import abc
import def
import x
from g import gg
from x import xx

Intra-Package

In a structure like this, how would you do import from another directory?
say from module-x.py import module-a

top-package/
    __init__.py
    sub-package-a/
        __init__.py
        module-x.py
        module-y.py
    sub-package-b/
        __init__.py
        module-a.py
        module-b.py

Here’s some examples doing relative imports in module-x

import module-y
from . import module-y
from .module-y import classA
from .. import sub-package-b
from ..subpackage-b import module-a
from ..subpackage-b.module-a import classB

Import an import

It is a common practice in C# to use import module or static class to stores all the global variables
used for settings, or even all the modules. In Python it would be something like:
constant.py

import module_a
import module_b
import module_c

GLOBAL_VAR_MAX = 50
GLOBAL_VAR_MIN = 10
GLOBAL_VAR_TIMEOUT = 2000

GLOBAL_NAME = r'random name'

# or even
class Constant(object):
    gravity = 9.8
    is_true = True

With this setup, all the module in the same project would just import the constant module and have access to
all the imports and variable. I thought this was a neat way to make code cleaner by getting rid of all the duplicated imports
that might happen.

there are also some voices against it:

  • based on the style guide: Constants are usually defined on a module level
  • also, suggestions have mentioned to refrain from using class as it could be instantiated which makes no sense.
  • unless there’s a valid reason for all those modules to be collected under a common name. If not, then they should
    be kept separately. This is due to documentation, as other people open your file, they don’t get information on
    what is getting imported (what is needed)

Same module import multiple times

So if multiple files are importing the same module separately, does python optimize the import?

Yes, python modules are considered as singletons, no matter how many times you import them they get initialized only once.
unless reload is being called

Reference

Stack Overflow - constants in Python: at the root of the module or in a namespace inside the module?

Stack Overflow - in python, do you need to import modules in each split file?

Stack Overflow - Python: Importing an “import file”

Stack Overflow - Does python optimize modules when they are imported multiple times?

Stack Overflow - Why can I import successfully without init.py?

Stack Overflow - relative path not working even with init.py

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-01-04 13:23:24  更:2022-01-04 13:23:28 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/16 3:22:45-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码