John Zwinck
John Zwinck

Reputation: 249454

Get data members in Python module, as help() does

This Python:

data = {}

def f():
    pass

import sys

help(sys.modules[__name__])

Prints this:

Help on built-in module __main__:

NAME
    __main__

FILE
    /foo/bar.py

FUNCTIONS
    f()

DATA
    data = {}

My question is, how can I get a list of "data" objects like the help function does? I looked at inspect.getmembers() but it returns things I don't want, and writing a predicate for it seems like it should not be necessary.

Upvotes: 2

Views: 335

Answers (2)

Ned Batchelder
Ned Batchelder

Reputation: 375814

You can read the code behind the help(module) implementation: http://hg.python.org/cpython/file/110b38c36a31/Lib/pydoc.py#l1060

It's kind of complicated though....

Upvotes: 2

Gareth Latty
Gareth Latty

Reputation: 89077

You can use the locals() builtin in the global scope.

>>> data = {}
>>> locals()
{'__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', 'data': {}, '__doc__': None, '__package__': None}

It's worth noting that you will obviously need to filter out the built-in values, which is easily done:

>>> {name: value for name, value in locals().items() if not name.startswith("__")}
{'data': {}}

Note that generally any problem you will solve like this will be better solved by using a better data structure.

Upvotes: 0

Related Questions