问题
I have just learnt about importing modules, and I am a bit confused about the wildcard import.
from module_name import *
I do not understand the reason of using it at all, I see people saying not to use it at all.
Could someone clarify what it really means, and why would one use it?
回答1:
According to [Python 3.Docs]: Modules - More on Modules (emphasis is mine):
There is even a variant to import all names that a module defines:
>>> from fibo import * >>> fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This imports all names except those beginning with an underscore (
_
). In most cases Python programmers do not use this facility since it introduces an unknown set of names into the interpreter, possibly hiding some things you have already defined.Note that in general the practice of importing
*
from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.
So, it means: importing all (check the above page for the __all__ variable meaning) symbols exported by a module / package into the current namespace.
Generally (as the above states), it's used when one is in the console and wants to save time by not importing everything needed, "manually".
It's also used by some who don't know what to import (so they import everything, since they don't really know what they're doing - there are exceptions of course, but those are rare).
Anyway, probably this is the most eloquent example (as it only relies on Python): illustrating its pitfalls:
>>> with open("out.txt", "w") as f: ... f.write("DON'T USE wildcard imports!") ... 27 >>> >>> from os import * >>> >>> with open("out.txt", "w") as f: ... f.write("USING wildcard imports ...") ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: an integer is required (got type str)
The wildcard import shadows:
- [Python 3.Docs]: Built-in Functions - open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
by:
- [Python 3.Docs]: os.open(path, flags, mode=0o777, *, dir_fd=None)
Things can get even messier when dealing with 3rd-party modules (where the collision hit chance can grow exponentially).
回答2:
This is used for importing everything from the module. The reason why you are recommended not to use it, is because it can get confusing as to where the function or class you are using came from. Moreover, some things might have the same name in different modules, and importing them like this would overwrite the one previously imported.
回答3:
from module import *
generally imports evey name from a given module (though the module may use __all__
to restrict that). It's generally best avoided, since this set of names may change over time, possibly changing the names available to your code.
I do sometimes use it in interactive sessions as a convenience, though.
来源:https://stackoverflow.com/questions/55722260/what-is-the-reason-for-using-a-wildcard-import