Wednesday, May 12, 2021

Python - Different ways to import Python modules

 

In Python each file ended with extension .py is called a python module. these modules can be imported into your code in the below mentioned ways.

To keep it in short and sweet listed below with short explanation for the same.

source.py
def func1(num1):
print(f"func1 - {num1}")

def func2(num2):
print(f"func2 - {num2}")

I am trying to import source python module in to destination.py module. 

Method 1

import source
source.func1(10)
source.func2(20)

Method 2

import source as nickname
nickname.func1(100)
nickname.func2(200)

 Method 3:

from source import func1

func1(100)
func2(200) #NameError: name 'func2' is not defined
Method 4
from source import *
func1(100)
func2(200)

Thank You

No comments:

Post a Comment