Python中两种带别名的import导入方式是否完全一致?
import module.submodule as alias and from module import submodule as alias identical? Great question—your observation is spot-on for the tkinter.ttk case you tested, but let’s break down whether these two approaches are always the same, or just coincidentally similar here.
Short Answer for Your Test Case
In the specific scenario you tried with tkinter.ttk, yes—these two import methods behave exactly the same in practice. Both end up binding the tkinter.ttk module object to the name my, so calling my.Button() will produce identical results every time.
Under-the-Hood Differences (That Rarely Matter... Until They Do)
While the end result is the same for standard library submodules like ttk, there are subtle differences in how Python resolves the imports that can cause behavior changes in edge cases:
1. How Python looks up the target
import tkinter.ttk as my: Python first loads thetkinterpackage, then navigates to itsttksubmodule (loading it if needed), and finally binds that submodule tomy. This path always targets the submodule directly, regardless of what’s intkinter’s__init__.py.from tkinter import ttk as my: Python looks for an object namedttkwithin thetkinterpackage’s namespace. Usually, this is the submodule, but iftkinter/__init__.pyhad a variable or function namedttk(e.g.,ttk = "some custom value"), this import would grab that object instead of the submodule.
2. Module caching side effects
Both imports will load tkinter and tkinter.ttk into Python’s module cache (sys.modules) if they aren’t already there. The only minor difference is that import tkinter.ttk as my doesn’t add tkinter to your current namespace (you’d have to import tkinter separately if you wanted to use it), while from tkinter import ttk as my also doesn’t add tkinter to your namespace—so this is rarely a practical distinction.
Example of When They Do Differ
Let’s imagine a custom package where the __init__.py overrides a submodule name:
mypackage/ __init__.py utils.py
In mypackage/__init__.py:
# This overrides the "utils" submodule name in the package namespace utils = "I'm a string, not a module!"
In mypackage/utils.py:
def greet(): print("Hello from the utils module!")
Now try the two imports:
import mypackage.utils as u:uwill be theutils.pymodule—you can callu.greet()successfully.from mypackage import utils as u:uwill be the string"I'm a string, not a module!"—callingu.greet()will throw an AttributeError.
Final Takeaway
For most everyday use cases (especially with standard library modules like tkinter.ttk), these two import styles are interchangeable and produce identical results. The only time you’ll see a difference is when a package’s __init__.py defines a name that conflicts with one of its submodules.
内容的提问来源于stack exchange,提问作者RisingUnderDog

