1

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.

7
  • 2
    Do you know about from module import * ? Commented Mar 17, 2013 at 14:13
  • Thanks I assumed that was done for functions implicitly. Now it works. Is there a way to limit the import to all functions? Because it also has other types, etc. Just wondering. Commented Mar 17, 2013 at 14:15
  • 1
    In your module, you can define a variable named __all__ that contains names of everything that will be imported by *. Commented Mar 17, 2013 at 14:17
  • The names imported from a module may be controlled by setting the __all__ variable in the module itself. This allows the designer of modules to define what should be imported by import *. A module user has to accept the predefined list (if any) or explicitly provide a list of names to import from module import name1,name2,.... Commented Mar 17, 2013 at 14:18
  • That's a neat trick, although it's not my module, so can't modify it. It's ok though, was just curious. Commented Mar 17, 2013 at 14:18

1 Answer 1

6

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 *.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.