How to create a module in Python and import it?

Python modules are files containing python codes that define methods, classes and variables. These files have the .py extension and increase the reusability of codes.
You must be familiar with various built-in modules in Python like os, time, random, math etc.
Have you wondered if you can create your own modules for common code snippets that you use frequently? Well, in this tutorial you will learn exactly the same(create a module in python and import it).

Create a module in Python

Writing code for a module in Python is just like writing any other python program.
First of all, create a file and name it using the extension ‘.py’. That is, module_name.py. Once this is done, you can type code involving methods, variables and classes inside it. Once you create a module, import it to use in your programs.

First, let us see an example of creating a module with a method.

So, let us create a file called egmodule.py, in which we define a method ‘example()‘.

def example():
    print("This is an example module!")

Now that the module has been created, let us use it in another program by importing it.

import egmodule
egmodule.example()
This is an example module!

As you can see, we define the example() method in egmodule.py and then import it to print the corresponding message. Observe how we invoke the method by referencing the module name and following it with a dot(.).

Note: Please ensure that you define both your module and program in the same directory.

Further, let us try to implement variables in a module and use them.
Let us add a variable ‘name’ in the egmodule.py module.

def example():
    print("This is an example module!")
name= "CodeSpeedy"

We can then run a program that displays the variable defined in the module as shown below.

import egmodule
egmodule.example()
print(egmodule.name)
This is an example module!
CodeSpeedy

Lastly, let us see how to define and import classes through a Python module.
We define a class ‘options‘ in the egmodule.py module.

def example():
    print("This is an example module!")
name= "CodeSpeedy"
class options:
    def __init__(self, types, language):
        self.types = types
        self.language = language
    def about(self):
        print("This is " + self.types + " in " + self.language)

We then access the class’s methods and attributes as shown.

import egmodule
egmodule.example()
print(egmodule.name)
c=egmodule.options("article", "python")
c.about()
This is an example module!
CodeSpeedy
This is article in python

 Importing a module

  1. Using the import statement:
    Syntax: import module_name
    In this case, you can use the methods and variables defined inside the module by using the dot operator as done in all the above examples.

    import egmodule
    egmodule.example()
    This is an example module!
  2. Import using aliases(by renaming):
    Syntax: import module_name as alias_name
    Renaming egmodule as em can save us typing time in some cases.

    import egmodule as em
    em.example()
    This is an example module!
    
  3. Importing specific names from a module:
    Syntax: from module_name import name, where name can be the name of method/class/variable.
    In this case, we don’t need to use the dot operator for referencing.

    from egmodule import name
    print(name)
    CodeSpeedy
  4. Importing all names/methods from a module:
    Syntax: from module_name import *
    The * can be used to import all the methods/variables/classes present in the specified module.

    from egmodule import *
    example()
    This is an example module!
    
    

NOTE: The dir() method can be used to list all the members defined/present in the module.

dir(egmodule)
['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'example',
 'name',
 'options']

 

Do read, Python Modules

Leave a Reply

Your email address will not be published.