Reputation: 33857
I have some python module, that I import as:
from mygraph.draw import pixel
The file structure looks like that:
mygraph/
__init__.py
draw.py
and draw.py
contains def pixel()
Now, I want to add another function, line()
, and I want to import it as
from mygraph.draw import line
I can simply add line
to draw.py
. But, I would like to have line()
in a separate file line.py
and not mess with draw.py. But, if I place it in a separate file, it will be imported as
from mygraph.line import line
and that is not what I want...
Is it possible to "alias" somehow the line.py
so it is visible in draw
module, but is in separete file? I thought about adding a dummy function in draw
def line():
return real_line.line()
but in this case I won't have a "docstring" from the original line
, and I will loose some performance on calling the real line function.
Upvotes: 4
Views: 1628
Reputation: 14497
Structure like this will make more sense for you:
mygraph/
__init__.py
draw/
__init__.py
pixel.py
line.py
Then in draw/__init__.py
you would have code like this:
from mygraph.draw.pixel import pixel, redpixel, greenpixel
from mygraph.draw.line import line, redline, greenline
And it is convenient to use your package:
from mygraph.draw import redpixel, redline
Be aware of circular imports. For example if line
needs pixel
to work, and you do import pixel
in line.py
, you cannot do import line
in pixel.py
, because you are running to into circular imports.
Upvotes: 4
Reputation: 77474
Try this in your draw.py
module:
from line import line
and you should be able to invoke it as mygraph.draw.line
, and import it the way you wanted.
I do this a lot in my __init__.py
files: expose the primary API this way.
Upvotes: 5
Reputation: 14482
An easy way would be to add the following lines to draw.py
:
from line import line
In this case you can import line
from draw.py
too.
Upvotes: 3