Reputation: 331250
If you have a module like module
, can you bypass it and use the functions available inside without using the module?
I imported the module, but the compiler still complains not having to find function
. I still have to use module.function()
.
It has many more functions, so I don't want to redefine them one by one but just avoid typing module
if possible.
Upvotes: 1
Views: 3877
Reputation: 174662
Importing in Python just adds stuff to your namespace. How you qualify imported names is the difference between import foo
and from foo import bar
.
In the first case, you would only import the module name foo
, and that's how you would reach anything in it, which is why you need to do foo.bar()
. The second case, you explicitly import only bar
, and now you can call it thus: bar()
.
from foo import *
will import all importable names (those defined in a special variable __all__
) into the current namespace. This, although works - is not recommend because you may end up accidentally overwriting an existing name.
foo = 42
from bar import * # bar contains a `foo`
print foo # whatever is from `bar`
The best practice is to import whatever you need:
from foo import a,b,c,d,e,f,g
Or you can alias the name
import foo as imported_foo
Bottom line - try to avoid from foo import *
.
Upvotes: 6