Python Modules – Types and Examples

FREE Online Courses: Dive into Knowledge for Free. Learn More!

A module is a file with the extension .py and contains executable Python or C code. A module contains several Python statements and expressions. We can use pre-defined variables, functions, and classes with the help of modules. This saves a lot of developing time and provides reusability of code. Most modules are designed to be concise, unambiguous, and are meant to solve specific problems of developers.

Types of Modules in Python

There are two types of modules in Python, they are built-in modules and user-defined modules.

1. Built-in Modules in Python

Modules that are pre-defined are called built-in modules. We don’t have to create these modules in order to use them. Built-in modules are mostly written in C language. All built-in modules are available in the Python Standard Library.

Few examples of built-in modules are:

  • math module
  • os module
  • random module
  • datetime module

2. User-defined Modules in Python

User-defined modules are modules that we create. These are custom-made modules created specifically to cater to the needs of a certain project.

Let us see how we create these user-defined modules.

a. Creating Modules in python

Creating a module is a simple two-step process. First, we need to write some Python code in a file using any text editor or an IDE. Then, we need to save the file with the extension .py.

We can name the file anything but the extension should always be .py. For example, we can name the file hello.py. We can call this the hello module.

Example on creating a module in Python

First, we write some Python code in a file.

Code in file hello.py

def greet(name=""):
   print(f"Hello! Nice to meet you {name}")

Second, we save the file with the name hello and extension .py.

That’s it! We created our module, hello and it is ready to use whenever we want.

Importing Modules in Python

Modules are meant to be used with other files. To use a module, we need to first import it. There are two different keywords we can use to import a module. They are “import” and “from”.

1. Using Keyword: import

The simplest way to import a module is to use the import keyword followed by the module name.

Syntax

import ModuleName

Example on using import keyword

If we want to import the module hello.py into another file main.py, we use the following code.

Code in file main.py

import hello

Access the module’s objects in Python

The import keyword creates a reference to the specified module name. Hence, to access its objects, we need to use the module name and a dot operator.

Syntax to access a variable in Python

ModuleName.VariableName

Syntax to call a function in Python

ModuleName.FunctionName()

Example on accessing a module’s object using import keyword

Code in file main.py

import hello

hello.greet()

Output

Hello! Nice to meet you

In the above code example, we called the function greet(), which is inside the hello.py module, from the main.py script.

Importing Multiple objects in Python

We can access multiple objects of a module by using the import keyword.

Example on importing multiple objects using import keyword

Code in file main.py

import math

print(math.log2(2))
print(math.sqrt(16))
print(math.pow(2,4))

Output

1.0
4.0
16.0

Importing Multiple Modules in Python

We can import multiple modules using a single import keyword.

Syntax

import moduleName1, moduleName2,..,ModuleNameN

Example on importing multiple modules using import keyword

code in file main.py

import hello, math, random

hello.greet()
print(math.sqrt(4))
print(random.randint(1, 2)) #generates a random number

Output

Hello! Nice to meet you
2.0
2

In the above code example, we used the import keyword to import multiple modules

Pros of using import keyword in Python

  • It is the simplest and easiest way of importing.
  • With just one line, we can access multiple objects of multiple modules.

Cons of using import keyword in Python

  • We need to specify the module name every time we want to access an object from the module. This makes the code clunky, lengthy, and time-consuming.

Using Keyword From in Python

When we need to import only a certain part of the module and not the entire module, we can use the from keyword. This is the most precise way of importing.

Syntax

from ModuleName import ObjectName

Example on using from keyword

Code in file main.py

from hello import greet

Access the module’s objects

The keyword from imports the module and creates references to the specified functions. Hence we can directly access them.

Example on accessing a module’s object using from keyword

Code in file main.py

from hello import greet
greet()

Output

Hello! Nice to meet you

In the above code example, we called the function greet() without using the module name.

Importing Multiple objects in Python

We can import multiple objects of a module by using the from keyword.

Syntax

from ModuleName import ObjectName1,ObjectName2,..,ObjectNameN

Example on importing multiple objects using from keyword

Code in file main.py

from math import sqrt, exp, log2

print(sqrt(4))
print(exp(0))
print(log2(2))

Output

2.0
1.0
1.0

In the above code example, we called multiple functions without using the module name.

Importing Multiple Modules in Python

Importing multiple modules using a single from keyword is not possible. We need to use multiple from keywords to import multiple modules.

Example on importing multiple modules using from keyword

Code in file main.py

from hello import greet
from math import sqrt
greet()
print(sqrt(4))

Output

Hello! Nice to meet you
2.0

Pros of using from keyword in Python

  • Since we have to specify every object name while importing, this is the most unambiguous and precise way of importing.
  • It is the recommended way of importing.

Cons of using from keyword in Python

  • We need to write multiple from statements to import multiple modules.
  • When we need to import a large number of objects from a module, we have to specify all those objects’ names in the from statement. This is a time-consuming process.

from Keyword with Asterisk (*) in Python

We can also import the entire module using the from keyword. To do this we need to use the symbol asterisk (*). This allows us to import multiple objects without specifying their names in the from import statement.

Syntax

from ModuleName import *

Example on using asterisk(*) with from keyword

Code in file main.py

from math import *

Access the module’s objects

This makes python import the specified module and creates references to all the functions and attributes inside the module. We do not need to use the module name to access any of the module’s attributes. This is the main difference to the import keyword.

Example on accessing module’s objects using * with from keyword

Code in file main.py

from math import *

print(sqrt(4))
print(pow(2, 2))
print(log2(2))

Output

2.0
4.0
1.0

In the above code example, although we used the from keyword, we called multiple functions without specifying their names in the import statement.

Pros of using * with from keyword in Python

  • This brings the best of both worlds. Like the import statement, we can import an entire module. Like the from statement, we can access any function without using the module name.

Cons of using * with from keyword in Python

  • When two modules have an object with the same name, the object from the latest imported module replaces the object from the earlier imported module.
  • Possibility of namespace collisions.

Aliasing Modules in Python

We often need to import modules with lengthy or difficult names. To help in those cases, Python provides us the ability to rename the module.

We can do this by using the keyword as

Syntax

import ModuleName as NewModuleName

Example on renaming a module

Code in file main.py

import numpy as np
print(np.log2(2))

Output

1.0

In the above code example, we renamed the module numpy to np.

Aliasing Objects of a Module

We can also rename specific objects of a module by combining from and as keywords

Syntax

from ModuleName import ObjectName as NewObjectName

Example on renaming objects of a module

Code in file main.py

from random import randint as rt
print(rt(1, 10)) # Generates a random number between 1 and 10

Output

7

In the above code example, we renamed a function randint to rt from the module random.

PYTHONPATH

PYTHONPATH is an environmental variable in Python. The variable contains a list of directories. These are the directories Python uses to search for a module.

Accessing the PYTHONPATH variable

To access and view the PYTHONPATH variable, we use the following code.

Code in file main.py

import os
print(os.environ['PYTHONPATH'].split(os.pathsep))

Output

[‘/Users/apple/PycharmProjects/PythonGeeks, ‘/Users/apple/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/203.7148.72/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend’, ‘/Users/apple/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/203.7148.72/PyCharm.app/Contents/plugins/python/helpers/pycharm_display’]

We can see in the above code, Python printed a list of directories.

Modifying the PYTHONPATH variable

We can add a new directory to the PYTHONPATH variable by using the below syntax.

Syntax

set PYTHONPATH = directory

Example on modifying the PYTHONPATH variable

Code for Windows in file main.py

set PYTHONPATH = c:\python3\newfolder;

Code for Unix in file main.py

set PYTHONPATH = /usr/local/lib/newfolder

In the above code example, we added the directory to the PYTHONPATH list.

How Python Finds a Module?

Python starts searching for the specified module as soon we run a script containing an import statement. The search involves three steps.

1. First, Python searches in the current directory i.e., the directory that contains the script we ran. Python stops the search if it finds the module.

2. If it didn’t find the module in the current directory, then Python searches in all directories present in the PYTHONPATH variable.

3. If it didn’t find the module in PYTHONPATH directories, then Python searches in the default directory. Each OS has its default directory. For example, the default directory of Unix is ‘/user/local/lib/Python/’.

If it still didn’t find the module, then Python stops the search and displays a ModuleNotFoundError.

Python Compiles Only Once

When we import a module, Python compiles the module and saves the compiled file in a cache directory. Python does this to save time and resources. The name of the compiled file is in the following format.

Name Format
module_name.compiler_version.extension

The compiler version and extension depend on the compiler we are using.

For example, if we are using the compiler Cython version 27 to compile the module named hello, then we get the following filename.

Filename
hello.cython-27.pyc

If we are using Jython version 2, then we get the following filename.

Filename
hello.jython-2.class

Running a Python Module without Importing

It is possible to run a module without importing. We just need to run them like normal scripts, but modules don’t contain any function calls or print statements, so they don’t output anything.

To get an output, we need to add a block of printable code to our module. For example, adding a function call or a print statement to our module makes it execute the function or print something like a normal script.

Example on running a module without importing in Python

Code in file hello.py

def greet(name=""):
print(f"Hello! Nice to meet you {name}")

greet()

Output

Hello! Nice to meet you

In the above code example, our module hello.py is being executed normally without importing.

Complications from importing normal scripts

Making our module run like a normal script creates a small complication. When we import the module, Python executes the function call and runs the function. This causes unnecessary outputs to the console.

Example on complications from importing normal scripts in Python

Code in file main.py

import hello

Output

Hello! Nice to meet you

In the above code example, although we intend to only import the module, Python still executed the function and printed a string.

if __name__ == “__main__”:

Python provides an attribute __name__ to avoid this complication. __name__ contains the name of the file. Its behavior is a bit different depending on how we use it.

Using __name__ to get the name of an imported module returns the name of the module.

Example on using __name__ attribute in a script

Code in file main.py

import hello

print("Name of the module is", hello.__name__)

Output

Hello! Nice to meet you
Name of the module is hello

Using __name__ to get the name of the file that we are currently running returns a string “__main__” instead of the actual name of the file.

Example on using __name__ attribute in a module

Code in file hello.py

def greet(name=""):
print(f"Hello! Nice to meet you {name}")
greet()

print(__name__)

Output

Hello! Nice to meet you
__main__

In the above code example, although our file name is hello, printing the __name__ attribute resulted in a string “__main__”.

We can use this to our advantage and solve our previously encountered problem. To do that, we need to add an if-condition and change our code a bit.

Example on using __name__ attribute in if statement

code in file hello.py

def greet(name=""):
print(f"Hello! Nice to meet you {name}")

if __name__ == "__main__":
greet()

In the above code example, the if-condition checks whether the file name is “__main__” or not.

The file name becomes “__main__” only if we are running that file. So, the if-condition is actually checking whether we are running the file or importing the file.

If we are running the file, then the if-condition becomes true and Python executes the function call. If we are importing the file, the if-condition becomes false and Python doesn’t execute the function call.

Example on running the file hello.py

Code in hello.py

def greet(name=""):
print(f"Hello! Nice to meet you {name}")

if __name__ == "__main__":
greet()

Output

Hello! Nice to meet you

Example on importing the file hello.py

Code in main.py

import hello
print("Imported Function didn't execute")

Output

Imported Function didn’t execute

In the above code examples, the greet() function got executed when we ran the file directly but when we imported the file, greek() didn’t get executed.

Reload() in Python

In Python, it is not possible to import the same file more than once. No matter how many import statements we write, Python only imports once. This can be seen in the below code.

Example on importing multiple times using import keyword

Code in file hello.py

def greet(name=""):
print(f"Hello! Nice to meet you {name}")
greet()

Code in file main.py

import hello
import hello

Output

Hello! Nice to meet you

In the above code example, although we wrote import hello twice, Python only executed it once.

In order to execute the import statement again, we need to use a Python built-in function called reload(). The function reload() takes the module name as an argument and re-executes the import statement of the passed module.

This is a built-in function till Python2.x. So we can use this directly without importing any module.

We need to import the imp module to use this function if our Python version is between 2.x and 3.3. We need to import the importlib module if our Python version is greater than 3.3.

Example on importing multiple times using reload() function

Code in file main.py

from importlib import reload
import hello

reload(hello)

Output

Hello! Nice to meet you
Hello! Nice to meet you

In the above code example, the reload() function executed the import statement again.

dir() in Python

dir() is a Python built-in function. It takes the name of a module as an argument and returns a sorted list of the names of all attributes and functions present in the passed module.

Syntax

dir(ModuleName)

Example on using dir()

Code in file hello.py

def greet(name=""):
print(f"Hello! Nice to meet you {name}")

Code in file main.py

import hello
print(dir(hello))

Output

[‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘greet’]

In the above code example, dir() returned the list of variables and functions present inside our module hello.py. We can see our function greet() in the list.

Types of Variables in Python

1. Namespace

A Namespace is a dictionary containing the names of variables and their values. The name of the variable is key and the value of the variable is value in the dictionary.

For example, the namespace of a module containing variables x = 10, and y = “PythonGeeks” is {x: 10, y: “PythonGeeks”}.

2. Global variables

Variables that are defined outside a function are called global variables. The global namespace contains all global variables’ names and their values.

We can use the globals() function to return the global namespace. We can call globals() from either inside or outside of a function.

3. Local Variables

Variables that are defined inside a function are called local variables. The local namespace contains all local variables’ names and their values.

We can use the locals() function to return the local namespace. locals() should be called inside a function. Calling locals() from outside a function returns the same dictionary that we get when we call globals().

Example of types of variables

Code in file main.py

site = 'Google'

def getSite():
   oursite = "PythonGeeks"
   print("locals :", locals())
   print("globals :", globals())

getSite()

Output

locals : {‘oursite’: ‘PythonGeeks’}
globals : {‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <_frozen_importlib_external.SourceFileLoader object at 0x1056e3670>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘__file__’: ‘/Users/apple/PycharmProjects/PythonGeeks/main.py’, ‘__cached__’: None, ‘site’: ‘Google’, ‘getSite’: <function getSite at 0x1056b2280>}

In the above code, site is the global variable and oursite is the local variable.

Accessing Variables in Python

When we import a module, we can only access the global variables of that module. Python raises an AttributeError when we try to access a local variable.

Example on accessing variables in Python

Code in file hello.py

myname = "Catherine" # global variable

def greet():
   name = "Nithya"  # local variable
   print(f"Hello! Nice to meet you {name}")

Code in file main.py

import hello

print(hello.myname) # Accessing global variable
print(hello.name) # Accessing local variable

Output

Catherine
AttributeError: module ‘hello’ has no attribute ‘name’

In the above code example, Python returned an AttributeError because we tried to access the local variable name. We can access the global variable myname without any problem.

Python Built-in Attributes for Modules

Python provides several built-in attributes to help us better understand a module. These attributes contain details of the module like name, and location. A few of those attributes are as below:

1. __name__

This attribute contains the name of the module. We already learned about __name__ and its uses in the previous section.

2. __doc__

The attribute __doc__ returns the documentation string of the module.

Example on using __doc__ attribute

Code in file main.py

import math

print(math.__doc__)

Output

This module provides access to the mathematical functions defined by the C standard.

We can define the documentation string by placing triple-double-quotations before and after a string at the top of the module.

Example of adding documentation to the file

Code in file hello.py

"""This module greets people"""

def greet(name=""):
print(f"Hello! Nice to meet you {name}")

Code in file main.py

import hello
print(hello.__doc__)

Output

This module greets people

3. __file__

The attribute __file__ contains the path of the module.

Example on using __file__ attribute

Code in file main.py

import hello
print(hello.__file__)

Output

/Users/apple/PythonGeeks/hello.py

4. __dict__

The attribute is similar to the dir() function. It contains a dictionary of attributes, functions, and other objects in the module. It has more items in the dictionary than the dir() function.

Example on using __dict__ attribute

Code in file main.py

import math
print(math.__dict__)

Output

{‘__name__’: ‘math’, ‘__doc__’: ‘This module provides access to the mathematical functions\ndefined by the C standard.’, ‘__package__’: ”, ‘__loader__’: <_frozen_importlib_external.ExtensionFileLoader object at 0x10406a970>, ‘__spec__’: ModuleSpec(name=’math’, loader=<_frozen_importlib_external.ExtensionFileLoader object at 0x10406a970>, origin=’/usr/local/opt/[email protected]/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/math.cpython-38-darwin.so’), ‘acos’: <built-in function acos>, ‘acosh’: <built-in function acosh>, ‘asin’: <built-in function asin>, ‘asinh’: <built-in function asinh>, ‘atan’: <built-in function atan>, ‘atan2’: <built-in function atan2>, ‘atanh’: <built-in function atanh>, ‘ceil’: <built-in function ceil>, ‘copysign’: <built-in function copysign>, ‘cos’: <built-in function cos>, ‘cosh’: <built-in function cosh>, ‘degrees’: <built-in function degrees>, ‘dist’: <built-in function dist>, ‘erf’: <built-in function erf>, ‘erfc’: <built-in function erfc>, ‘exp’: <built-in function exp>, ‘expm1’: <built-in function expm1>, ‘fabs’: <built-in function fabs>, ‘factorial’: <built-in function factorial>, ‘floor’: <built-in function floor>, ‘fmod’: <built-in function fmod>, ‘frexp’: <built-in function frexp>, ‘fsum’: <built-in function fsum>, ‘gamma’: <built-in function gamma>, ‘gcd’: <built-in function gcd>, ‘hypot’: <built-in function hypot>, ‘isclose’: <built-in function isclose>, ‘isfinite’: <built-in function isfinite>, ‘isinf’: <built-in function isinf>, ‘isnan’: <built-in function isnan>, ‘isqrt’: <built-in function isqrt>, ‘ldexp’: <built-in function ldexp>, ‘lgamma’: <built-in function lgamma>, ‘log’: <built-in function log>, ‘log1p’: <built-in function log1p>, ‘log10’: <built-in function log10>, ‘log2’: <built-in function log2>, ‘modf’: <built-in function modf>, ‘pow’: <built-in function pow>, ‘radians’: <built-in function radians>, ‘remainder’: <built-in function remainder>, ‘sin’: <built-in function sin>, ‘sinh’: <built-in function sinh>, ‘sqrt’: <built-in function sqrt>, ‘tan’: <built-in function tan>, ‘tanh’: <built-in function tanh>, ‘trunc’: <built-in function trunc>, ‘prod’: <built-in function prod>, ‘perm’: <built-in function perm>, ‘comb’: <built-in function comb>, ‘pi’: 3.141592653589793, ‘e’: 2.718281828459045, ‘tau’: 6.283185307179586, ‘inf’: inf, ‘nan’: nan, ‘__file__’: ‘/usr/local/opt/[email protected]/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/math.cpython-38-darwin.so’}

In the above code example, __dict__ returned a dictionary of everything present in the module math.

Advantages of Modules in Python

Using modules has so many advantages. A few of those are:

1. Modules help us break down a problem into several smaller problems. This helps us develop programs easier and faster.

2. When we are working in teams, it is easier to divide work. Each team member can create one module and at the end, we can connect all those modules together to solve the final big problem.

3. Since modules are problem-specific and concise, they are easier to modify and maintain.

4. Modules provide reusability. We can define some functions in a module and we can use those functions in any file we want just by importing the module.

5. Modules have a separate namespace. This helps us avoid overriding variables and functions.

Packages in python

What are Python packages?

The Package provides an application development environment by creating a hierarchical directory structure that contains various modules and sub-packages.

In simple terms, packages are a collection of modules and sub-packages.

Why do we need packages in python?

When we are working on a big or complex project, we often end up with several different modules. It is tiresome to use, maintain and organize that many modules.

Thankfully, Python provides us with an easy solution called packages. We can group, organize and use different modules effortlessly using packages.

Packages also provide us the ability to have only one import statement to access all functions from all modules in a package.

Creating Packages in Python

A package is nothing more than a special directory. So the first step in creating a package is creating a directory. Let us create a directory called Geography.

The next step is to create a few modules in the directory. Let us create two modules countries.py and states.py with the following codes.

Example on creating a package

Code in file countries.py

def getCountry():
print("Country is America")

Code in file states.py

def getState():
print("State is California")

The directories of countries.py and states.py are Geography/countries.py, Geography/states.py respectively.

The final step in making this ordinary directory a package is creating a package constructor file in the directory.

Package Constructor

A package constructor is a module named __init__.py. This module initializes the package as soon as we import it.

To create a package constructor, we need to create an __init__.py file and add the following code to the file.

Example on creating a constructor for a package

Code in file __init__.py

from Geography.countries import getCountry
from Geography.states import getState

Python runs the __init__.py file as soon as we import it. After creating the __init__.py, the directory of __init__.py is Geography/__init__.py

Finally, our package Geography is created with three modules, countries.py, states.py, and __init__.py.

Using packages in python

We can use any type of import statement to access the package.

Example on using packages

Code in file main.py

import Geography as geo

geo.getCountry()
geo.getState()

Output

Country is America
State is California

In the above code package, we only needed to import one package to access the functions in modules countries.py and states.py.

Sub-packages in Python

Sub-packages are nothing but packages inside other packages. Let us create a sub-package Climatology inside our previously created package Geography.

Example on creating a sub-package

The sub-package Climatology has the following files with code

Code in file cities.py

def getCities():
print("The city is Los Angeles")

Code in file temperatures.py

def getTemp():
print("The temperature is 22 degrees celsius")

Code in file __init__.py

from Geography.Climatology.cities import getCities
from Geography.Climatology.temperatures import getTemp

The directories of the above files are:

  • Geography/Climatology/cities.py
  • Geography/Climatology/temperatures.py
  • Geography/Climatology/__init__.py

To use this sub-package, we need to modify the __init__.py file present in our package Geography.

Modifying the Geography/__init__.py file

Code in file Geography/__init__.py

from Geography.countries import getCountry
from Geography.states import getState
from Geography.Climatology import getCities, getTemp

Since we modified the file, let’s access the sub-package.

Example on using the sub-package

Code in file main.py

import Geography as geo

geo.getCountry()
geo.getState()
geo.getCities()
geo.getTemp()

Output

Country is America
State is California
The city is Los Angeles
The temperature is 22 degrees celsius

In the above code example, we accessed the functions from the sub-package and other modules by importing only one package.

Modules vs Packages in Python

Few differences between Modules and Packages are:

  • A Module is a .py file containing Python code whereas a Package is a directory containing multiple modules and sub-packages.
  • To create a package, we need to create an __init__.py file. There is no such requirement for creating modules.

Functions, Modules, and Packages

The functions, modules, and packages all follow the same concept. They aim to give the reusability of code with as much ease as possible.

Although they look and work differently, their basic principle is the same.

  • Function contains multiple Python statements and expressions
  • Module contains multiple Python functions.
  • Package contains multiple Python modules.

Interview Questions on Python Modules

Q1. Write a module named mathstools. The module should contain the following functions.
add() – Takes two arguments and returns their sum.
square() – Takes an argument and returns its square value.
multiply() – Takes two arguments and returns their product.

Ans1.

File: mathstools.py

def add(x, y):
   return x + y

def square(x):
   return pow(x, 2)

def product(x, y):
   return x * y

Q2. Create a Python file named testmath and import a module named mathstools and call the functions add(x, y), square(x), and product(x, y) from that module. Don’t use the asterisk and also don’t use the import keyword to import the entire module.

Ans 2.

File: testmath.py

from hello import add, square, product

print(add(20 ,4))
print(square(4))
print(product(5, 5))

Output

24
16
25

Q3. Create a python file named renamemodule and import any built-in module. Rename the module to x and call anyone function from the module.

Ans 3.

File: renamemodule.py

import random as x
print(x.randint(1, 100))

Output

16

Q4. Create a module with a docstring. Create another Python file, import the module and print the docstring of that module.

Ans 4.

File: mymodule007.py

""" Hey! This is a docstring """

File: mymain007.py

import mymodule007
print(mymodule007.__doc__)

Output

Hey! This is a docstring

Q5. Create a package named mypackage24 with modules mymodule1, mymodule2, mymodule3. All three modules should have a function that returns their name. Create one more Python file, import the package and run all three functions. You should get the following output.

Output

mypackage24.mymodule1
mypackage24.mymodule2
mypackage24.mymodule3

Ans 5.

File: mypackage24/mymodule1.py

def name1():
print(__name__)

File: mypackage24/mymodule2.py

def name2():
print(__name__)

File: mypackage24/mymodule3.py

def name3():
print(__name__)

File: mypackage24/__init__.py

from mypackage24.mymodule1 import name1
from mypackage24.mymodule2 import name2
from mypackage24.mymodule3 import name3

File: main.py

import mypackage24

mypackage24.name1()
mypackage24.name2()
mypackage24.name3()

Output

mypackage24.mymodule1
mypackage24.mymodule2
mypackage24.mymodule3

Python Modules Quiz

Conclusion

In this article, we learned about Pythonmodules, their types, ways to import them, and their advantages. We learned about the attributes and a few built-in functions that are useful while dealing with modules. We also discussed packages and the relationship between functions, modules, and packages.

Furthermore, if you have any queries, feel free to share them with us in the comment section.

Did you like our efforts? If Yes, please give PythonGeeks 5 Stars on Google | Facebook

1 Response

  1. teresa says:

    read

Leave a Reply

Your email address will not be published. Required fields are marked *