In the context of this exercise, how can we see all the objects and functions in a module?
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.
# 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.
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.
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__()
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’m sure someone may have already covered this here, but I’ll give it a mention anyway.
When you’re in the Python interpreter (indicated by >>> after you type ‘python’ or ‘python3’ at the prompt), if you’re looking for help on a particular module or function or object, you have to use the help() function by either typing in the name of the argument as a string or import that module first so you can use that name without the string.
For example, to get help on the math module without importing the module first:
You can hit the End key to reach the bottom of the text. Just hit the Q key to get out of the text.
Hopefully this helps anyone needing some more clarification.