用于创建和导入虚拟模块的python包。
virtualmod的Python项目详细描述
虚拟内存
用于创建和导入虚拟模块的python包。
安装
pip install virtualmod
示例
模块对象
使用virtualmod
手动创建和注册模块。
importvirtualmod# Create a new empty virtual modulemodule=virtualmod.create_module('custom_module')# Add attribute to modulemodule.key='value'# Use decorator to add a function to the module# NOTE: You can use `add_to_module(module, name='new_name')` to override the module attribute name@virtualmod.add_to_module(module)defmodule_function(name):print('Hello',name)# Use decorator to add a class to the module@virtualmod.add_to_module(module)classModuleClass:pass# Import and use our virtual moduleimportcustom_moduleprint('Key:',custom_module.key)custom_module.module_function('virtualmod')print(custom_module.ModuleClass())
类定义
virtualmod
还具有使用类定义来定义虚拟模块的能力。
importvirtualmod# Use class definition to define our virtual module "custom_module"classCustomModule(virtualmod.VirtualModule):# Define the module's name (would be "CustomModule" otherwise)__module_name__='custom_module'# Add an attributekey='value'# Add a function# NOTE: There is no `cls` or `self`defmodule_function(name):print('Hello',name)# Add a class to the moduleclassModuleClass:pass# Import and use our virtual moduleimportcustom_moduleprint('Key:',custom_module.key)custom_module.module_function('virtualmod')print(custom_module.ModuleClass())
重写现有模块virtualmod
的模块查找程序在标准内置查找程序之前注册。
这意味着,如果你注册一个模块,在一个现有模块的名称下,你会发现并加载第一个
importvirtualmod# Create a virtual module under the name "socket"my_socket=virtualmod.create_module('socket')# Import socket moduleimportsocket# Test if the loaded socket module is the one we createdprint(socketismy_socket)
推荐PyPI第三方库
virtualmod
的模块查找程序在标准内置查找程序之前注册。
这意味着,如果你注册一个模块,在一个现有模块的名称下,你会发现并加载第一个
importvirtualmod# Create a virtual module under the name "socket"my_socket=virtualmod.create_module('socket')# Import socket moduleimportsocket# Test if the loaded socket module is the one we createdprint(socketismy_socket)