CJlano
CJlano

Reputation: 1572

Use a python module from within a package

I have some difficulties with python module/package usage in my code. The code is here: https://github.com/cjlano/svg

.
└── svg
    ├── geometry.py
    ├── __init__.py
    ├── LICENSE
    ├── README.md
    ├── svg.py
    ├── svg.test.py
    └── tests
        └── [...]

In the module svg I need to use the module geometry. As this module did not exist in the beginning when all the code was in svg.py, I decided to import the entire geometry namespace into svg (from geometry import *).

My issue is that, when I import the svg module from my package, it works well in python2 but fails in python3:

Python 2.7.5 (default, Sep  6 2013, 09:59:46) 
[GCC 4.8.1 20130725 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from svg import svg
>>> help(svg)

Gives me access to the svg module documentation. Whereas

Python 3.3.2 (default, Sep  6 2013, 09:35:59) 
[GCC 4.8.1 20130725 (prerelease)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from svg import svg
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "./svg/svg.py", line 27, in <module>
    from geometry import *
ImportError: No module named 'geometry'

Gives an error on import.

Any ideas on how to write my code to be usable in python3?

Thanks!

Upvotes: 0

Views: 888

Answers (2)

Lukas Graf
Lukas Graf

Reputation: 32580

Python 3 doesn't do implicit relative imports any more.

This means you need to either make the import of geometry in svg.py an explicit relative import, or better yet, change it to an absolute import:

from svg.geometry import *

As pointed out by @CJlano, this then also requires from __future__ import absolute_import for it to still work on Python 2.

Upvotes: 1

bogatron
bogatron

Reputation: 19169

It will work in both python 2.7 and 3.x if you use a relative import in svg.py:

from .geometry import *

Note the "." in front of the module name.

Upvotes: 1

Related Questions