How to Use __import__() Function in PythonPython Basics


__import__() function is used to dynamically load modules in runtime.

Tips: It is useful when the name of the module needed is unknown before runtime. In everyday Python programming, this function is rarely used and often discouraged.

Example

# importing random module 
# it is equivalent to "import random module" 
rand = __import__('random', globals(), locals(), [], 0) 
  
# Get random number in 0-1
print('Random number within 0-1:')
print(rand.random())
Output:

Random number within 0-1:
0.02289503978971319

Syntax

__import__(name[, globals[, locals[, fromlist[, level]]]])

Parameters

Name Description
name Module name

Return Value

Returns loaded module.

© 2024 Learnwithgpt.org, all rights reserved. Privacy Policy | Contact Us