module

module

There is a very large number of modules (sometimes called libraries) available for Python. Many are included with Python as standard and others can be downloaded and installed into Python. Standard Python libraries include modules for random numbers, database access, various Internet protocols, object serialization, and many more.

One consequence of having so many modules is that there is the potential for conflict, for example, if two modules have a function of the same name. To avoid such conflicts, when importing a module, you can specify how much of the module is accessible.

For example, if you just use a command like this: import random, there is no possibility of any conflicts because you will only be able to access any functions or variables in the module by prefixing them with random.:

import random
random.randint(1, 6)
2

If, on the other hand, you use this command: from random import *, everything in the module will be accessible without to put anything in front of it. Unless you know what all the functions are in all the modules you are using, there is a much greater chance of conflict.

In between these two extremes, you can explicitly specify those components of a module that you need within a program so that they can be conveniently used without any prefix.

For example:
from random import randint
print(randint(1,6))
3

A third option is to use the as keyword to provide a more convenient or meaningful name for the module when referencing it.
import random as R
R.randint(1, 6)


(The number generated will be between the two arguments (inclusive)--in this case, simulating a gaming dice.)

No comments:

Post a Comment