简体   繁体   English

如何使python帮助系统在动态创建的模块中显示动态创建的类?

[英]How do I make the python help system show dynamically created classes in my dynamically created module?

I am dynamically creating a python module with dynamically created classes within that module. 我正在动态创建一个python模块,并在该模块中动态创建了类。 However, when using the help function in python, the classes do not appear. 但是,在python中使用帮助功能时,这些类不会出现。 Here is an example of the issue. 这是问题的一个例子。

import imp
Foo = imp.new_module("Foo")
Foo.Bar = type('Bar', (object,), dict(x=10, y=20))
help(Foo)

This shows the following. 显示以下内容。

Help on module Foo:

NAME
    Foo

FILE
    (built-in)

I would like Bar to show up in the CLASSES section. 我希望Bar出现在CLASSES部分中。 How do I do that? 我怎么做?

Note that help(Foo.Bar) describes the class as in module __main__ . 请注意, help(Foo.Bar) in module __main__描述了该类。 Is that a clue? 这是一个线索吗?

Help on class Bar in module __main__:

class Bar(__builtin__.object)
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  x = 10
 |  
 |  y = 20

Set the __module__ of Bar : 设置Bar__module__

Foo.Bar.__module__ = Foo.__name__

and it'll show up. 它会出现。 help() filters out everything that is not part of the module, as per the .__module__ attribute. 根据.__module__属性, help()过滤掉属于模块的所有内容。 The rest is assumed to be external imports. 其余假定为外部进口。

If you set Foo.__all__ to include 'Bar' , then Bar will be listed in the CLASSES section: 如果将Foo.__all__设置为包括'Bar' ,则Bar将列在CLASSES部分中:

import imp
Foo = imp.new_module('Foo')
Foo.Bar = type('Bar', (object,), dict(x=10, y=20))
Foo.__all__ = ['Bar']
help(Foo)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM