Modules#

Using a module#

Create a file called mymodule.py with the following

Example:

1def greeting(name):
2    print("Hello, " + name)

In our main program we can import the module and can call the function defined in the module.

Example:

 1#!/usr/bin/env python3
 2
 3import mymodule
 4
 5def main():
 6    mymodule.greeting("John")
 7
 8
 9if __name__ == "__main__":
10    main()

Using variable in modules#

If we extent mymodule.py with the following

Example:

1person = {
2"name": "John",
3"age": 42,
4"country": "Ireland"
5}

We can now access the variable person and use age defined within person

Example:

 1#!/usr/bin/env python3
 2
 3import mymodule
 4
 5def main():
 6    age = mymodule.person["age"]
 7    print(age)
 8
 9
10if __name__ == "__main__":
11    main()

Output:

42

Import from a module#

You can also import a certain section from a module

Example:

 1#!/usr/bin/env python3
 2
 3from mymodule import person
 4
 5def main():
 6    print(person["age"])
 7
 8
 9if __name__ == "__main__":
10    main()

Rename a module#

We can rename a module during import

Example:

 1#!/usr/bin/env python3
 2
 3import mymodule as abc
 4
 5def main():
 6    age = abc.person["age"]
 7    print(age)
 8
 9
10if __name__ == "__main__":
11    main()

Built-in modules#

Example:

 1#!/usr/bin/env python3
 2
 3import platform
 4
 5def main():
 6    x = platform.system()
 7    print(x)
 8
 9
10if __name__ == "__main__":
11    main()

Example:

 1#!/usr/bin/env python3
 2
 3import platform
 4
 5def main():
 6    x = dir(platform)
 7    print(x)
 8
 9
10if __name__ == "__main__":
11    main()