Course contentsShow
← Python
Lesson 172 of 1,0603. Functions and ModularizationFree lesson

Managing Namespace Conflicts with Import Statements

Learners will utilize various import syntaxes to access external code while preventing naming collisions between local variables and imported functions.

In this lesson, you will learn how to use specific import syntaxes to safely integrate external code into your project while avoiding naming collisions.

When you import code from a module, you bring new names into your current namespace. A "namespace conflict" occurs when an imported function or variable has the same name as one you have already defined in your local scope. If this happens, your local definition will be overwritten, leading to unexpected bugs.

Using Aliasing to Resolve Conflicts

The most straightforward way to avoid these collisions is the as keyword, which allows you to rename an import as you bring it into your program.

Imagine you have a function called calculate() in your own code, but you also need to use a calculate() function from a library named data_tools. If you perform a simple from data_tools import calculate, your local calculate function will be lost. Instead, you can do this:

from data_tools import calculate as compute_data

def calculate(numbers):
    return sum(numbers) / len(numbers)

# Now you can use both without conflict!
my_result = calculate([1, 2, 3])
tool_result = compute_data("input.csv")

Importing the Full Module

If you want to avoid importing specific names into your local namespace entirely, you can import the module itself. By using import module_name, the functions inside remain hidden behind the module's name as a prefix.

import math
import my_math_library

# No collision, because both are accessed via their module namespaces
print(math.sqrt(16))
print(my_math_library.sqrt(16))

By prefixing the function with the module name, you ensure that Python knows exactly which version of the function you intend to call. This approach keeps your code readable and ensures that your local variables stay protected from external naming choices. When you manage your imports carefully, you maintain full control over the names available in your current scope.

Key Takeaway: Use the as keyword to rename conflicting imports or import the entire module to use namespacing as a prefix, ensuring your local variables remain untouched.