Yogeswaran
Yogeswaran

Reputation: 365

Calling dir function on a module

When I did a dir to find the list of methods in boltons I got the below output

>>> import boltons
>>> dir(boltons)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']

When I explicitly did

>>> from boltons.strutils import camel2under
>>> dir(boltons)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'strutils']

found that strutils getting added to attribute of boltons

Why is strutils not showing before explicit import?

Upvotes: 3

Views: 149

Answers (1)

Henry Heath
Henry Heath

Reputation: 1082

From the docs on what dir does:

With an argument, attempt to return a list of valid attributes for that object.

When we import the boltons package we can see that strutils is not an attribute on the boltons object. Therefore we do not expect it to show up in dir(boltons).

>>>import boltons
>>>getattr(boltons, 'strutils')
AttributeError: module 'boltons' has no attribute 'strutils'

The docs on importing submodules say:

For example, if package spam has a submodule foo, after importing spam.foo, spam will have an attribute foo which is bound to the submodule.

Importing a submodule creates an attribute on the package. In your example:

>>>import boltons
>>>getattr(boltons, 'strutils')
AttributeError: module 'boltons' has no attribute 'strutils'
>>>from boltons.strutils import camel2under
>>>getattr(boltons, 'strutils')
<module 'boltons.strutils' from '/usr/local/lib/python3.5/site-packages/boltons/strutils.py'>

Therefore in this case we do expect strutils to show up in dir(boltons)

Upvotes: 3

Related Questions