← Back to Python Course | Chapter 8: Modules & Packages | Lesson 2 of 6

Python import Statement

import statement किसी दूसरी file का code आपकी file में ले आता है, जैसे पड़ोसी से कोई tool उधार लेना। आप पूरा toolbox ले सकते हैं या सिर्फ़ एक tool।
Syntax
python
import module_name
import module_name as alias
from module_name import name1, name2

Basic Import Statement

'import module_name' पूरा module load करता है और आपको उससे इस्तेमाल की जाने वाली हर चीज़ के आगे module का नाम लगाना पड़ता है, जैसे math.sqrt(16) -- इससे बहुत सारे imports वाली files में भी यह साफ़ रहता है कि हर function कहाँ से आया है।

उदाहरण: Basic Import Statement

python
import math
print(math.sqrt(16))

'from' से Specific Items Import करना

'from module import name' किसी specific function, class, या variable को सीधे आपकी file के namespace में ले आता है, ताकि आप math. prefix के बिना sqrt(16) call कर सकें -- यह सुविधाजनक है, पर file बड़ी होने पर यह याद रखना मुश्किल हो जाता है कि कोई नाम कहाँ से आया।

उदाहरण: Import Specific Items with 'from'

python
from math import sqrt
print(sqrt(16))

'as' से Imports का नाम बदलना

'import numpy as np' किसी module (या import किए गए नाम) को एक छोटा local alias देता है, इसी वजह से ecosystem में 'import numpy as np' और 'import pandas as pd' जैसा convention है -- यह उस library को लगातार इस्तेमाल करने वाली file में बहुत सारे keystrokes बचाता है।

उदाहरण: Renaming Imports using 'as'

python
import math as m
print(m.pi)

Wildcard Imports

'from module import *' किसी module के हर public नाम को एक साथ सीधे आपके namespace में ले आता है, लेकिन ऐसा करने से यह पता लगाना मुश्किल हो जाता है कि कौन-सा function कहाँ से आया, और यह जोखिम रहता है कि यह पहले से define किए गए नामों को चुपचाप overwrite कर दे -- ज़्यादातर style guides इससे बचने की सलाह देती हैं।

उदाहरण: Wildcard Imports

python
from math import *
print(sqrt(25))  # unclear which module sqrt came from

Conditional और Dynamic Imports

चूँकि import एक साधारण statement है, आप इसे किसी function, if block, या try/except के अंदर रख सकते हैं -- इसका उपयोग optional dependencies के लिए (अगर कोई library install नहीं है तो gracefully fallback करने के लिए) या किसी import की लागत को तब तक टालने के लिए किया जाता है जब तक वह code path वाकई न चले।

उदाहरण: Conditional and Dynamic Imports

python
try:
    import ujson as json_lib  # preferred faster library, if it's installed
except ImportError:
    import json as json_lib  # fallback to the standard library

print(json_lib.dumps({"a": 1}))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.