Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

python - What is the reason for using a wildcard import?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to [Python.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:

by:

Things can get even messier when dealing with 3rd-party modules (where the collision hit chance can grow exponentially).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...