首页 > 编程语言 >Python - sys.modules

Python - sys.modules

时间:2024-12-29 15:56:52浏览次数:5  
标签:Python modules module sys import math

In Python, sys.modules is a dictionary that maps module names to the modules themselves. This dictionary is used internally by the Python interpreter to track which modules are loaded in memory.

When you import a module using the import statement, Python checks sys.modules first to see if the module has already been loaded. If it has, Python uses the existing module in sys.modules rather than reloading it. If the module is not in sys.modules, Python will load it from disk, execute the code, and then add it to the sys.modules dictionary.

Key Points About sys.modules:

  1. Caching Modules: Once a module is imported, it is stored in sys.modules. This means subsequent imports of the same module are much faster since Python can skip the loading and parsing steps.

  2. Accessing sys.modules: You can access sys.modules like a regular dictionary. The key is the module name, and the value is the module object.

  3. Example Usage:

    python import sys import math # Load the math module # Check if 'math' is in sys.modules print('math' in sys.modules) # Output: True # Retrieve the module object for 'math' math_module = sys.modules['math'] print(math_module) # Output: <module 'math' (built-in)>
  4. Manipulating sys.modules: While sys.modules is primarily for internal use, you can manipulate it in certain scenarios (e.g., to mock modules in tests, load modules dynamically, or handle module imports in a custom way).

Example of How Python Uses sys.modules:

Let's say you import a module like my_module:

python import my_module
  • Python first checks if my_module is already present in sys.modules.
  • If my_module is found, Python uses the cached version and skips the loading process.
  • If my_module is not found, Python looks for the module in the standard library and custom locations. Once it's found and executed, it is added to sys.modules.

Example of Adding or Removing Modules from sys.modules:

You can also manually add or remove modules from sys.modules, but this is not common practice for regular Python code.

python import sys # Adding a module manually sys.modules['my_module'] = some_module_object # some_module_object is an imported module # Removing a module del sys.modules['my_module']

Example: sys.modules to Prevent Re-Importing

You can use sys.modules to prevent re-importing a module. For example, to "mock" a module or manipulate it dynamically:

python import sys import math # Remove 'math' from sys.modules to force re-import del sys.modules['math'] import math # This will re-import the math module because it was removed from sys.modules

Why sys.modules Matters:

  • Performance Optimization: By caching modules in sys.modules, Python avoids the overhead of re-importing a module that has already been loaded.
  • Custom Import Behavior: You can modify sys.modules to implement custom import logic, such as dynamic loading or mocking modules during tests.
  • Debugging: When debugging issues related to imports, sys.modules can be a useful tool to see which modules are loaded and their corresponding module objects.

Summary:

sys.modules is a crucial internal dictionary that Python uses to manage imported modules. It caches modules after they are loaded to optimize subsequent imports. While you typically don’t need to interact with it directly, understanding how it works can be useful for advanced usage, debugging, and custom import behavior.

标签:Python,modules,module,sys,import,math
From: https://www.cnblogs.com/zhangzhihui/p/18639067

相关文章

  • [Python/GPT/AI] Ollama指南
    概述:Ollama基本介绍:OllamaOllama是一个支持在Windows、Linux和MacOS上本地运行大语言模型的工具。它允许用户非常方便地运行和使用各种大语言模型,比如Qwen模型等。用户只需一行命令就可以启动大语言模型。主要特点跨平台支持Windows、Linux、MacOS系统。提供了丰富......
  • 2024-12-24《Scala编程语言和python的对比》
     Scala和Python都是通用编程语言,但它们有一些区别,涉及到语法、执行速度、类型系统等方面。下面是Scala和Python的一些对比:类型系统:Scala:是一种静态类型语言,编译时会检查类型。Scala的类型系统相对较强,允许程序员定义和使用复杂的类型结构。Python:是一种动态类型......
  • Python-IO(转载)
    Python文件I/O本章只讲述所有基本的I/O函数,更多函数请参考Python标准文档。打印到屏幕最简单的输出方法是用print语句,你可以给它传递零个或多个用逗号隔开的表达式。此函数把你传递的表达式转换成一个字符串表达式,并将结果写到标准输出如下:#!/usr/bin/python#-*-coding:......
  • PYTHON语言学习笔记(基础语法篇)
    Python学习笔记序言主要是以小甲鱼的视频为主,https://space.bilibili.com/314076440一些特性多次调用方法是从左到右.而参数是函数则先执行参数.一行如果要多个赋值,用;隔开input().split()IO看我放在另一个地方的文档.<D:\Document\md\PYTHON\IO.md>数据类型变量没什......
  • sysstat 源码编译安装与配置
    下载cd/usr/local/srcsudowgethttps://github.com/sysstat/sysstat/releases/download/v12.5.7/sysstat-12.5.7.tar.xz解压sudotar-xvfsysstat-12.5.7.tar.xzcdsysstat-12.5.7编译安装mkdir-p/usr/local/sysstatsudo./configure--prefix=/usr/local/sysstatss......
  • Python机器学习:糖尿病数据集分析与预测
    文章目录一、数据处理1、加载数据集        使用pandas加载本地CSV文件,展示数据的前5行、结构信息和描述性统计量,帮助理解数据特征的分布情况。file_path="E:\data.csv"data=pd.read_csv(file_path)print("数据集前5行:\n",data.head())print("\n数据......
  • 基于Python控制台开发的图像灰度化和滤波处理系统
    以下是一个适合大一、大二学生基于Python控制台开发的图像灰度化和滤波处理系统的课程设计程序。该程序使用Python的Pillow和NumPy库,实现了加载图像、灰度化处理和应用滤波操作等功能,提供一个控制台交互的用户界面。程序功能描述加载图像:从用户提供的文件路径加载图像。显示......
  • 10个简单但很有用的Python装饰器
    10个简单但很有用的Python装饰器https://zhuanlan.zhihu.com/p/6474274711、@timer:测量执行时间优化代码性能是非常重要的。@timer装饰器可以帮助我们跟踪特定函数的执行时间。通过用这个装饰器包装函数,我可以快速识别瓶颈并优化代码的关键部分。下面是它的工作原理:impor......
  • python 赋值、深拷贝浅拷贝及切片使用
    赋值、深浅拷贝先复习一下赋值与深浅拷贝i=[1,2,1,3,[1,2]]j=i#赋值k=i.copy()#浅拷贝m=copy.deepcopy(i)#深拷贝#赋值,二者物理地址相同,一方变化另一方同步变化j.pop(0)print(i,j)[2,1,3,[1,2]][2,1,3,[1,2]]#取浅拷贝,二者物理......
  • Python环境管理的新选择:UV和Pixi,高性能Python环境管理方案
    近期Python生态系统发生了重要变化,特别是在包管理领域。Anaconda对其商业许可证政策进行了调整,要求大型非营利组织(员工超过200人)需要为使用其默认包仓库的每位用户获取商业许可。这一变化促使开发社区开始寻找更开放的解决方案,特别是考虑到Python本身及其大多数包都是开源的这一事......