Python Modules
The module is same as the code library. A file containing a set of functions which can be include in our applications.
Create a Module:
To create a module we just save the code file with the extension .py
Example:
Save the below code with greeting.py
def hello(name): print("Hello, " + name)
Use a Module:
By using the import statement, we can use the function in other modules.
Example:
Import the module named greeting, and call the hello function:
import greeting greeting.hello("John")
Output:
Hello John
When we use the function from the module, we use the syntax: module_name.function.name
Variables in Module:
The module can contain functions and variables of all types namely arrays, dictionaries, objects, etc.
Example:
Save the below code mycode.py
person = { "name": "John", "age": 28, "college": "Stanford" }
Import the module named mycode in new code and we can access the variables as shown below:
import mycode a = mycode.person["college"] print(a)
Output:
Stanford
Naming a Module
The module file can be named whatever we like, but it must have the file extension .py
Re-naming a Module
We can create an alias when we import a module, by using the as keyword
Example:
Create an alias mc for mycode
import mycode as mc a = mc.person["college"] print(a)
Output:
Stanford
Built-in Modules
There are many built-in functions in python and can be imported whenever its needed.
Example:
Import and use the platform module:
import platform a = platform.system() print(a)
Output:
Windows