管理模块导出方式的实用程序
publicize的Python项目详细描述
公布
帮助管理模块导入或导出方式的实用程序集
适用于当前主要的cpython版本2.7和3.7。
详细的错误消息使查找名称冲突变得容易。
显著减少样板文件,特别是使用star_export、star_import、public_constants和import_from_object。
当源代码发生更改,但无法或不希望重新启动解释器时,可以简化动态重新加载模块的过程
安装
$ pip install publicize
功能
- import_as_copy(mod_or_name:[str, object]) -> module:
导入mod或u name的浅拷贝
- import_from_object(obj, overwrite=False) -> dict
假装obj是一个模块并导入其公共属性
- public(*objects:[str, object], overwrite=False) -> objects[0]
将对象(或名称)标记为公共对象并自动将其附加到__all__。 可以用作带或不带右括号的装饰符。
有两种不同的使用方法:
- ^{tt10}$
- Simple decorator for functions/classes. Adds the wrapped object’s ^{tt11}$ attribute to ^{tt9}$
- ^{tt13}$
- If an object is passed as an argument, all names that refer to that object will be added to ^{tt9}$. If a string is passed, the name will be added assuming the reference actually exists.
- public constants(**constants)-> constants:
定义公共全局变量,将它们的名称添加到__all__。
- public_from_import(module:[str, ModuleType], *names, overwrite=False) ->{**imported}:
from module import names并将导入的名称添加到__all__。
- publish_module(module:[str, ModuleType], overwrite=False) -> module:
发布使用from module import *
获得的所有内容
- reimport_module(module:[str, ModuleType]) -> module:
清除模块的指令并重新导入。
- reverse_star_import(module) -> None:
删除将使用from module import *
导入的内容
- safe_star_import(module) ->{**imported}:
>p>^ t2121}$,它不会覆盖现有名称 - star_export(*private_modules, ignore_list=None, export_private=True, export_metadata=False, caller=None):
强制导出器(默认为调用方)导出几乎所有内容
- star_import(module:[str, ModuleType], overwrite=False, module=False, prefix=None, id_mod=None, ignore_private=False, import_metadata=False) -> [dict, {**imported}]:
忽略默认的{tt29}$机制以导入几乎所有内容。
如果prefix为真,则它将位于导入名称的前面。
如果overwrite为false,则会引发错误而不是重写。
如果ignore_private为真,则用 忽略下划线。
如果import_metadata为true,则模块元数据属性如 __author__和__version__被导入。
如果module为真,则返回模块本身,否则返回dict 导入的映射:对象名称。
模块的特殊属性,如__path__、__file__和 __all__从未导入。
示例用法
# in colors.py from publicize import * public_from_import('enum', 'Enum') @public class Colors(Enum): RED = red = 'red' BLUE = blue = 'blue' GREEN = green = 'green' COLOR_LIST = [*Colors] COLOR_DICT=public_constants(**Colors.__members__) CHARTREUSE = GREEN CYAN = BLUE CARMINE = RED public(CHARTREUSE, CYAN, CARMINE) random = star_import('random', prefix='random_', module=True) def random_color(): return random_choice(COLOR_LIST) def _get_valid_colors(): return {k for k, v in globals().items() if isinstance(v, Colors)}
>>> from publicize import *
>>> import colors
>>> colors_namespace = star_import('colors')
>>> colors.__all__
['BLUE', 'CARMINE', 'CHARTREUSE', 'CYAN', 'Colors', 'Enum', 'GREEN', 'RED', 'blue', 'green', 'red']
>>> CHARTREUSE
<Colors.GREEN: 'green'>
>>> COLOR_DICT['blue']
<Colors.BLUE: 'blue>
>>> old = CARMINE
>>> reverse_star_import('colors')
>>> reimport_module('colors').CARMINE is not old
True
>>> random_color()
<Colors.BLUE: 'blue'>
>>> _get_colors()
>>> {'BLUE', 'CHARTREUSE', 'GREEN', 'CARMINE', 'red', 'CYAN', 'green', 'blue', 'RED'}