Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you list the contents of the global namespace from within a module in python

In python, you can type dir() to get a list of the items in the global namespace, but the list is ugly, and it includes both public and private objects. I want to write a function (say pretty) that pretties it up. My function will live inside a module.

When I call pretty(dir()) I wind up pretty printing the objects in the module. Same for pretty(sorted(globals())). How can I get the list of the names of the objects in the global namespace (from within a module), so I can do my beautification?

I'm working in python3, if that matters.

EDIT: The first two answers that came back had to do with my controlling code in the module containing pretty. That's not what I want to do. I'm aiming at an experience like the following.

>>> foo = create_something()
>>> bar = create_something_else()
>>> create_lots_more_stuff()
>>> # Hmmmm I'd like to see a list of all the things I have created in my interactive python session.
>>> pretty(dir())
foo     bar
baz     qux
etc     etc_etc
like image 757
Steven Scott Avatar asked Oct 22 '25 01:10

Steven Scott


1 Answers

Rather than write a function to filter the dir() results, use the attributes __all__ and/or __dir__ to let your module publicly export the namespace explicitly, as described in PEP 0562.

# lib.py
deprecated_names = ["old_function", ...]
__all__ = ["new_function_one", "new_function_two", ...]

def new_function_one(arg, other):
   ...

def new_function_two(arg, other):
    ...

def __dir__():
    return sorted(__all__ + deprecated_names)

Usage:

# main.py
import lib

dir(lib)  # prints ["new_function_one", "new_function_two", "old_function", ...]

Note: The module level __dir__ hook requires Python 3.7+.


Edit: Perhaps you will be interested in the who and whos magic commands provided in an IPython interactive session. Demo shown below.

>>> who
Interactive namespace is empty.
>>> x = 123
>>> def foo():
...     pass
... 
... 
>>> who
foo  x   
>>> whos
Variable   Type        Data/Info
--------------------------------
foo        function    <function foo at 0x109b59158>
x          int         123
like image 166
wim Avatar answered Oct 23 '25 15:10

wim