Search code examples
pythonpython-module

Python Import everything from multiple file module into namespace


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.


Solution

  • 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