3

I'm trying to import multiple library files under a single alias, without the use of the init.py file (because it's apparently not supported by ROS).

Example:

Let's say we have the following files:

foo/
   __init__.py # This file is empty, used to categorize foo as a package.
   a.py
   b.py
   c.py
bar/
   example.py

a, b and c all include different functions which I need in example, so I import them

#example.py

from foo import a, b, c

a.fn1()
b.fn2()
c.fn3()

This works, but is there some way I could group them all under a single alias? Like so:

#example.py

from foo import [a, b, c] as foo

foo.fn1()
foo.fn2()
foo.fn3()

Again, I know this can be done by importing them under the init.py, but since our library is meant to work under ROS, we are currently unable to do as such without ending up with import errors when running in it ROS.

Thanks in advance.

2 Answers2

3

No.

One symbol in a script cannot refer to multiple modules at the same time.

And using different names for different modules is a much cleaner approach anyway. You can try to make your life a bit easier by using the wildcard import

from foo.a import *
from foo.b import *
from foo.c import *

fn1()
fn2()
fn3()

But this ends up polluting your namespace. I wouldn't recommend it.

rdas
  • 20,604
  • 6
  • 33
  • 46
  • No, I'd prefer using the a.fn1(), etc.. approach. Thx anyways. If you know of a way to actually make ROS work with __init__ level imports, that would be awesome XD. – Sebastien De Varennes May 01 '19 at 17:58
  • In your `__init__.py` You can try exporting the function symbols using `__all__`: https://stackoverflow.com/questions/44834/can-someone-explain-all-in-python – rdas May 01 '19 at 18:01
1

You could also try it (* not recommended):

from foo.a import fn1
from foo.b import fn2
from foo.c import fn3

fn1()
fn2()
fn3()
Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150