DavideC
DavideC

Reputation: 1

Importing a Python script within the same package, using a path containing the python package name in it

I have a python package (empty __init__.py inside) with several scripts, let's call it "mypackage" for simplifying. Then, I have two scripts, one called "utils.py", one call "view.py". I want to import utils in view, but, depending on the computer I am using (both Windows 10, both WinPython, both PyCharm, both 64bit), only one import form works, from the following two:

import utils as u

OR

import mypackage.utils as u

Why are not both of them working?

Upvotes: 0

Views: 107

Answers (2)

ems
ems

Reputation: 990

As mentioned in python documentation:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  1. The directory containing the input script (or the current directory when no file is specified).
  2. PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  3. The installation-dependent default.

When u write import mypackage.utils as u your mypackage directory should be specified in the PYTHONPATH environment variable.

Upvotes: 0

FHTMitchell
FHTMitchell

Reputation: 12156

Probably because one of your computers has python 2.x and the other has python 3.x. The way of importing modules in the same package changed with PEP 328.

The former way of doing this was with ambiguous relative imports

import utils

The problem is, does this refer to a module in the package or a stdlib module? This ambiguity meant that in python 3.0, it was decided that this syntax will always refer to installed packages in sys.path (known as absolute imports) and the syntax

from . import utils

To cope with this backward incompatible change, python introduced the

from __future__ import absolute_import

which you can put in python version >= 2.5 code at the top of your file and then can use the latter method.

As far as I am aware, import mypackage.utils should work so long as mypackage is in a directory in sys.path, so I think that should work no matter what.

Upvotes: 0

Related Questions