Modules & Libraries

 

What Are Modules?

  • Think of a module as a code library, a file that contains a set of functions and variables that you want to include in your application.

Built-in Modules:

  • Python has several built-in modules that you can import and use whenever you like.

Example: Importing a Built-in Module:

  • Import and use the platform module:

    python
    import platform
    
    x = platform.system()
    print(x)  # Output might be: 'Windows', 'Linux', or 'Darwin' (for Mac)
    

Using the dir() Function:

  • The dir() function lists all the function names (or variable names) in a module.

Example: Listing Names in a Module:

python
import platform

x = dir(platform)
print(x)  # Output: A list of all the defined names in the platform module

Importing Specific Parts from a Module:

  • You can choose to import only specific parts of a module using the from keyword.

Example: Importing Specific Parts:

  • Consider a module named mymodule with a function and a dictionary:

    python
    def greeting(name):
        print("Hello, " + name)
    
    person1 = {
        "name": "John",
        "age": 36,
        "country": "Norway"
    }
    
  • Importing only the person1 dictionary from mymodule:

    python
    from mymodule import person1
    
    print(person1["age"])  # Output: 36
    
    • Note: When importing using the from keyword, refer to the elements directly, not using the module name (e.g., person1["age"] instead of mymodule.person1["age"]).

Exercises:

  1. Import and Use a Built-in Module:
    • Import the math module and print the square root of 25.

      python
      import math
      
      print(math.sqrt(25))  # Output: 5.0
      
  2. List Names in a Module:
    • Use the dir() function to list all names in the random module.

      python
      import random
      
      print(dir(random))  # Output: A list of all defined names in the random module
      
  3. Import Specific Parts:
    • Create your own module with a function and a variable. Import only the variable and use it in your code.

      python
      # mymodule.py
      def greet(name):
          print("Hi, " + name)
      
      age = 15
      
      # main.py
      from mymodule import age
      
      print(age)  # Output: 15
      

Summary:

  • Modules help organize and reuse code in Python. They can be built-in or user-defined. Practice importing and using modules to understand how to leverage these useful libraries in your programs!