2

Let's say I have this:

script.py
module/
    __init__.py # just contains: __all__ = ['foo', 'bar']
    foo.py      # has a function called foo
    bar.py      # has a function called bar

If from script.py I do from module import * it works, but to call the foo or bar function I have to do foo.foo() / bar.bar().

Is there any way to have the foo and bar functions in the namespace, so I could call them by just doing foo() / bar() ?

Edit: The accepted answer works for this example case, but upon testing it doesn't seem to work if a file has a number in it's name.

For example, if you add a file named bar2.py with an function called hello to the module folder, and edit the __init__.py accordingly, then in the script.py you arent't be able to call the hello function directly (by just doing hello()) on the script, though you can do bar2.hello(), which works but isn't exactly what I want.

Edit: After a lot of testing I have found that by removing the __all__ and just keeping the imports it works.

mat
  • 314
  • 1
  • 3
  • 9

1 Answers1

4

In the __init__.py, write these two import statements:

from .foo import foo
from .bar import bar

Edit: if your module name have numbers in it.

from foo2 import foo
from bar2 import bar
  • I'd agree - but I'm not sure about the . e.g. .foo – Shane Gannon Mar 11 '19 at 21:30
  • What is that you are not sure of? ".foo" in "from" statement? – Sandhya Thotakura Mar 11 '19 at 21:33
  • Yes - it works. But it's not a practice I've come across before. Normally I'd use "from foo import foo" or "from foo import *" without a '.' – Shane Gannon Mar 11 '19 at 21:35
  • @ShaneGannon it's because they are in the same path. This is a relative import. Very useful when you have a lot of sub directories or to make sure it won't import from global installed packages – Gabriel Mar 11 '19 at 21:53
  • This works well, except when a file (in the case of the example, either the foo.py or the bar.py) has a number on their name, which is my case. – mat Mar 11 '19 at 21:57
  • @matdumb have a read of https://stackoverflow.com/questions/9090079/in-python-how-to-import-filename-starts-with-a-number - it should work for you – Shane Gannon Mar 11 '19 at 22:17
  • Even after trying that, I still get the same error. To be clear, the digit isn't the first character, It can be manually imported – mat Mar 11 '19 at 22:25
  • @matdumb: edit your question or create a new question with the error. So the community can help you. – Sandhya Thotakura Mar 11 '19 at 22:28