Matthew G.
Matthew G.

Reputation: 51

How do I avoid dir(my module) listing every package imported by my module in python?

Say I've written a python module called my_module:

# my_module.py

import numpy as np

def my_function():
    print("Hello, module!")

Then I import my_module and inspect it using the built-in function dir():

>>> import my_module
>>> dir(my_module)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'my_function', 'np']

np shows up in the list of names defined by my_module. This is annoying because I often want to use dir() to figure out what functions / classes, etc., are available via my_module. But in the result above, it's not clear to me how to tell whether np is native to my_module or if it's just some package that my_module imported, which (in my opinion) obfuscates the functionality of my_module.

So my question is, how do I structure my_module so that only the functions / classes / etc. it defines show up in dir(my_module)? Or equivalently, so that dir(my_module) doesn't print out every module imported in my_module.py?

I figure:

  1. This is possible, because dir(other popular packages) often don't appear to list their every import:

    >>> import scipy
    >>> print([x for x in dir(scipy) if "np" in x])
    ['nanpercentile', 'nanprod', 'nper', 'npv', 'unpackbits']
    
    >>> print([x for x in dir(scipy) if "numpy" in x])
    ['__numpy_version__', 'show_numpy_config']
    
  2. Or maybe they do, and that fact has just escaped me,

  3. Or I might be using dir() in a way that wasn't intended, and nobody cares if a bunch of imports appear in dir(my_module), and this is a waste of time.

Upvotes: 0

Views: 151

Answers (1)

tdelaney
tdelaney

Reputation: 77347

From the dir docs:

If the object is a module object, the list contains the names of the module’s attributes.

Imported modules are attributes, and so appear in the list. But this can be overridden

If the object has a method named dir(), this method will be called and must return the list of attributes.

So you could get the dir you want by writing a function that returns what you want.

# my_module.py

import numpy as np

def my_function():
    print("Hello, module!")

def __dir__():
    return ["my_function"]

But this is error prone... you have to keep up the list. I think a better way is to use python's doc strings and help instead. This is what its for. You control how chatty your documentation should be.

"""My module

Filled with my things.
"""

import numpy as np

def my_function():
    """Print the message"""
    print("Hello, module!")

example

>>> import my_module
>>> help(my_module)

Help on module my_module:

NAME
    my_module - My module

DESCRIPTION
    Filled with my things.

FUNCTIONS
    my_function()
        Print the message

FILE
    /home/td/tmp/a/my_module.py

Upvotes: 5

Related Questions