How can we see all the objects and functions in a module?

Question

In the context of this exercise, how can we see all the objects and functions in a module?

Answer

Python 3 provides some useful functions that let us view information about the attributes of a module.

You can use the dir() function, which returns a list of all the attributes of a specified module.

import math
print(dir(math))

# This would output all the attributes of the math module
# ['__doc__', '__file__', '__loader__', '__name__', '__package__', 
# '__spec__', 'acos', 'acosh', …]

You can also use the help() function, usually run in the Python shell, and you can provide it with an argument, which can be the name of a module, function, class, or other object. It will then provide an interactive help page about it.

>>>help(math)
8 Likes

What is the attributes which are surrounded by _ _?

'__doc__' # why this is surrounded by --
'acos' # why others are not?

What is the difference?

2 Likes

Also can we import objects anywhere in between the code?
say:

some lines of code
....
....
....
from module import object
....  # again some lines of code
...
...
1 Like

You can import modules and functions anywhere, as long as they are before the actual call to the function (and in the same or higher scope).
However, it is highly advisable to put all module imports in the beginning; at the very top of the code, in order to make them accessible everywhere in your program.

4 Likes

Mainly a naming convention. Special, or “magic”, objects or attributes that live in user-controlled namespaces. Never invent such names; only use them as documented.

A quote from one Jim Dennis at Quora

When conversing about Python among those who are intimately familiar with it, the __ is referred to as “dunder” (“Double UNDERscore”).

The convention has been to wrap identifiers (method names and some other types of identifer like name) in both leading and trailing dunders to denote that they are special to the language. The idea was to minimize the chances of colliding with programmer chosen method names and to keep the reserve word list relatively minimal as well.

There are a few exceptions to this convention. For example iterators define .next() rather than __next__() **Edit: from Python3 onwards, it is __next__()

2 Likes

Changed in Python 3. It’s now __next__().

3 Likes

This might sound dumb; but is there a way to know which modules or packages in python (or programming generally) available and their functions.
Also, I noticed the explanation, it mentioned that you can import a module using:
from package import module
But I have noticed that most codes I have seen just have;
import random or import math or similar syntax.
What is/are the difference(s) here?

I found out that I can see all the packages and module from the python shell. But what about the syntax.