【问题标题】:List extension modules without importing all列出扩展模块而不导入所有
【发布时间】:2019-07-30 12:22:54
【问题描述】:

使用 dir(module) 将列出我的模块的所有点选项,但是,某些模块需要您显式导入它才能在目录中查看它。

如何在不运行的情况下查看模块的所有扩展

from modulename import *

>>>import sklearn
>>>dir(sklearn)
['__SKLEARN_SETUP__',
 '__all__',
 ...
 ...
 'sys',
 'utils',
 'warnings']

之后

>>>import sklearn.tree
>>>dir(sklearn)
['__SKLEARN_SETUP__',
 '__all__',
 ...
 ...
 'sys',
 'tree', #Now it has been added to the list
 'utils',
 'warnings']

【问题讨论】:

  • 你看过importlib
  • sklearn.tree 是一个模块。在导入它之前,它实际上并不存在于 Python 中。您将不得不重建大部分导入机制来重现模块发现。请注意,包可以更改子模块的搜索路径 - 必须导入这些子模块才能重现导入行为。

标签: python python-3.x import module


【解决方案1】:

事实证明检查模块有一个很好的方法!

import inspect

inspect.getmembers(modulename)[1] # [1] gives us the stuff we want

对于 sklearn 案例:

>>>inspect.getmembers(sklearn)[1]

('__all__',
 ['calibration',
  'cluster',
  'covariance',
  ...
  ...
  'svm',
  'tree',  # There she is
  'discriminant_analysis',
  'impute',
  'compose',
  'clone',
  'get_config',
  'set_config',
  'config_context',
  'show_versions'])

【讨论】:

    猜你喜欢
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2018-02-24
    • 2017-12-26
    • 2013-04-05
    • 2020-06-08
    相关资源
    最近更新 更多