Junior
241
What is the difference between 'from foo import bar' and 'from foo import *'?
Answer from AI
sobes.tech AI
from foo import bar imports only the specific object bar from the module foo. This object becomes available by the name bar.
from foo import * imports all public names from the module foo. All these names become available in the current namespace without the foo. prefix. Names starting with an underscore (_) are considered private unless a __all__ list is defined.
# Example with 'from foo import bar'
# Suppose the module foo.py has a function bar and a variable baz
# foo.py:
# def bar():
# print("bar")
# baz = "baz"
from foo import bar
bar() # Call the function bar directly
# print(baz) # This will raise a NameError because baz was not imported
# Example with 'from foo import *'
# Using the same foo.py module
from foo import *
bar() # Call the function bar directly
print(baz) # variable baz is now accessible
Difference:
from foo import bar: Precise control over imported objects, less chance of name conflicts.from foo import *: Imports everything, convenient for interactive sessions or small scripts, but unsafe in large projects due to possible name overwriting and difficulty tracking object origins.
Using from foo import * is considered bad practice in production code, except when the module is explicitly designed for such import (e.g., UI frameworks).