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.

Joan Venge
  • 315,713
  • 212
  • 479
  • 689
  • 2
    Do you know about `from module import *` ? – isedev Mar 17 '13 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. – Joan Venge Mar 17 '13 at 14:15
  • 1
    In your `module`, you can define a variable named `__all__` that contains names of everything that will be imported by `*`. – Pavel Anossov Mar 17 '13 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,...`. – isedev Mar 17 '13 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. – Joan Venge Mar 17 '13 at 14:18
  • you could still do it by simply making your own module which imports the names you want, and then import that .. :P – wim Mar 17 '13 at 14:20
  • Thanks alot guys, I only needed a couple functions but still was curious. Being able to import everything by type seems useful though. – Joan Venge Mar 17 '13 at 14:28

1 Answers1

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

Community
  • 1
  • 1
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284