简体   繁体   中英

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. However, when using the help function in python, the classes do not appear. 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. How do I do that?

Note that help(Foo.Bar) describes the class as 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 :

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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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