It is recommended to not to use import *
in Python.
Can anyone please share the reason for that, so that I can avoid it doing next time?
It is recommended to not to use import *
in Python.
Can anyone please share the reason for that, so that I can avoid it doing next time?
These are all good answers. I'm going to add that when teaching new people to code in Python, dealing with
import *
is very difficult. Even if you or they didn't write the code, it's still a stumbling block.I teach children (about 8 years old) to program in Python to manipulate Minecraft. I like to give them a helpful coding environment to work with (Atom Editor) and teach REPL-driven development (via bpython). In Atom I find that the hints/completion works just as effectively as bpython. Luckily, unlike some other statistical analysis tools, Atom is not fooled by
import *
.However, lets take this example... In this wrapper they
from local_module import *
a bunch modules including this list of blocks. Let's ignore the risk of namespace collisions. By doingfrom mcpi.block import *
they make this entire list of obscure types of blocks something that you have to go look at to know what is available. If they had instead usedfrom mcpi import block
, then you could typewalls = block.
and then an autocomplete list would pop up.According to the Zen of Python:
... can't argue with that, surely?
http://docs.python.org/tutorial/modules.html
Because it puts a lot of stuff into your namespace (might shadow some other object from previous import and you won't know about it).
Because you don't know exactly what is imported and can't easily find from which module a certain thing was imported (readability).
Because you can't use cool tools like
pyflakes
to statically detect errors in your code.It is a very BAD practice for two reasons:
For point 1: Let's see an example of this:
Here, on seeing the code no one will get idea regarding from which module
b
,c
andd
actually belongs.On the other way, if you do it like:
It is much cleaner for you, and also the new person joining your team will have better idea.
For point 2: Let say both
module1
andmodule2
have variable asb
. When I do:Here the value from
module1
is lost. It will be hard to debug why the code is not working even ifb
is declared inmodule1
and I have written the code expecting my code to usemodule1.b
If you have same variables in different modules, and you do not want to import entire module, you may even do: