Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 636
Yogeswaran Avatar asked Sep 08 '26 06:09

Yogeswaran


1 Answers

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)

like image 172
Henry Heath Avatar answered Sep 10 '26 19:09

Henry Heath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!