Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the difference between import module and from module import name? import module और from module import name में क्या अंतर है?

Answer
StyleAccess patternNamespace
import modulemodule.nameKeeps names in the module's own namespace
from module import namename (directly)Brings the name into the current namespace
# import module - must prefix with module name
import math
print(math.sqrt(16))  # 4.0
print(math.pi)         # 3.14159...

# from module import name - use directly, no prefix
from math import sqrt, pi
print(sqrt(16))  # 4.0
print(pi)          # 3.14159...

# from module import * - imports EVERYTHING (generally discouraged)
from math import *
print(sqrt(16))  # works, but unclear WHERE sqrt came from when reading code
# Risk: name collisions if two modules define the same name

# import module as alias - common for long/frequently-used module names
import numpy as np
import pandas as pd
print(np.array([1, 2, 3]))

# from module import name as alias
from datetime import datetime as dt
print(dt.now())

# Best practice guidance:
# - 'import module' is clearer about WHERE functions come from (module.func())
# - 'from module import specific_name' is fine for a few well-known names
# - avoid 'import *' in production code - it hides where names originate
# and can silently override existing names in your namespace
StyleAccess patternNamespace
import modulemodule.nameNames module के namespace में रहते हैं
from module import nameसीधे nameName current namespace में आता है
import math
print(math.sqrt(16))  # 4.0
print(math.pi)

from math import sqrt, pi
print(sqrt(16))  # 4.0
print(pi)

# from module import * - सब कुछ import (आमतौर पर avoid करें)
from math import *
print(sqrt(16))  # काम करता है पर unclear कहां से आया

# import module as alias
import numpy as np
import pandas as pd
print(np.array([1, 2, 3]))

from datetime import datetime as dt
print(dt.now())

# Best practice:
# - 'import module' साफ़ बताता है कि function कहां से आया
# - 'import *' production code में avoid करें

Was this answer clear?