A module is a file containing Python definitions and statements which we can use in other Python programs.
A module is simply a “Python file” which contains code(functions, classes,lists etc) we can reuse in multiple Python programs.
Modules in Python can be of two types:
Modules allows us to use the functionality we need when we need it, and it keeps our code cleaner.
The functions we import as part of a module stays in their own namespace.(A namespace is simply a space within which all names are different from each other). The same name can be reused in different namespaces but two objects can’t have the same name within a single namespace.
For example, Many cities have a street called “Main Street”,
It is okay if 'different' cities have that 'same' street name but it’s very confusing if two streets in the same city have that same name!
Another example is the folder organization of file systems. One can have a file called "todo" in her work folder as well as her personal folder, but she knows which is which because of the folder it’s in; each folder has its own namespace for files.
One important note, human names are not part of a namespace that applies uniqueness; that’s why governments have invented unique identifiers to assign to people, like passport numbers.
In order to use Python modules, we have to import them into a Python program.
1)If we import morecode in a code, that imports everything in morecode.py. To invoke a function f1 that is defined in morecode.py, we can write morecode.f1().
Note that we have to explicitly mention morecode again, to specify that we want the f1 function from the morecode namespace.If we just write f1(), python will look for an f1 that was defined in the current file, rather than in morecode.py.
2)We can also give the imported module an alias (a different name, just for when we use it in our program). For example, after executing import morecode as mc,
we would invoke f1 as mc.f1(). We have now given the morecode module the alias mc. Programmers often do this to make code easier to type.
3)A third possibility for importing occurs when we only want to import SOME of the functionality from a module and we want to make those objects be part of the current module’s namespace.
For example, we could write from morecode import f1. Then we could invoke f1 without referencing morecode again: f1().