Editor settings

General settings

Save settings

Learn to program with Python

Avoid Naming Conflict #

When working with modules in Python, it's important to be mindful of potential name conflicts that can arise when importing values from different modules. Name conflicts occur when two or more imported values have the same name or when an imported value conflicts with an existing name in the current namespace.

For example:

from greetings import greet

def greet():
    print("Hello from greet function")

greet() # Hello from greet function

In the example above, we import the function greet() from the module greetings, and also define the greet() function in the current namespace. When we call greet() the last defined function will be used. That is why importing all values with import * is generally not recommended: it can cause unintended naming conflicts and is difficult to debug.

There are multiple ways to avoid naming conflict from importing in Python

Import the module instead of specific values #

This also helps us identify where the values are coming from.

import greetings

def greet():
    print("Hello from greet function")

greetings.greet("Dillan") # Hello Dillan!
greet() # Hello from greet function

Using as keyword #

We can alias imported values or the module name using the keyword as, for example:

from greetings import greet as gr

def greet():
    print("Hello from greet function")

gr("Dillan") # Hello Dillan!
greet() # Hello from greet function

Aliasing value names

import greetings as g

def greetings():
    print("Hello from greet function")

g.greet("Dillan") # Hello Dillan!
greetings() # Hello from greetings function

Aliasing module names


Exercise #

Alias the imported function to avoid naming conflict.

Tests #

  • Alias greet function from greetings module as g
  • Call the function g("Cory")
Output will be displayed here