
PYTHON — Import Module Objects Python
Social media is not about the exploitation of technology but service to community. — Simon Mainwaring
Importing Objects From a Module
In Python, when you import a module, you gain access to all the functions, classes, and variables defined in that module. However, there are times when you only need a specific name from a module. In such cases, you can import only that particular name using the from <module> import <some_name> syntax.
Let’s consider an example using a module called adder.py. This module contains two functions: add() and double(). Here's how you can import specific names from this module:
# main.py
from adder import add
result = add(2, 2)
print(result) # Output: 4In this example, only the add function is imported from the adder module, and it can be directly used in the main.py file without referencing the module name.
Now, let’s see how you can import multiple names from a module:
# main.py
from adder import add, double
result1 = add(2, 2)
result2 = double(4)
print(result1, result2) # Output: 4 8In this case, both the add and double functions are imported from the adder module and can be used directly in the main.py file.
It’s important to note that when importing specific names from a module, you have control over which names from the module you want to import. This can help in keeping the code clean and avoiding namespace collisions.
Summary
By using the from <module> import <some_name> syntax, you can selectively import objects from a module in Python. This allows you to control the names available in your current namespace and avoid potential naming conflicts.






