Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't the imports be absolute by default in python27?

Tags:

python

import

Imagine the directory structure:

/
    a/
        __init__.py
        b.py
        c.py
    c.py

File /a/b.py looks like:

import c
should_be_absolute = c

All the other files (including __init__) are empty.

When running a test script (using python 2.7):

import a.b
print a.b.should_be_absolute

with PYTHONPATH=/ from an empty directory (so nothing is added to PYTHONPATH from current directory) I get

<module 'a.c' from '/a/c.py'>

where according to PEP 328 and the statement import <> is always absolute I would expect:

<module 'c' from '/c.py'>

The output is as expected when I remove the /a/c.py file.

What am I missing? And if this is the correct behavior - how to import the c module from b (instead of a.c)?

Update:

According to python dev mailing list it appears to be a bug in the documentation. The imports are not absolute by default in python27.

like image 556
karolx Avatar asked Jul 30 '12 17:07

karolx


People also ask

What does absolute import do?

from __future__ import absolute_import isn't meant to stop top-level modules from shadowing top-level modules; it's supposed to stop package-internal modules from shadowing top-level modules. If you run the file as part of the pkg package, the package's internal files stop showing up as top-level.

How do imports work in Python?

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.

How do you use relative import in Python?

Relative imports use dot(.) notation to specify a location. Single dot specifies that the module is in the current directory, two dots indicate that module is in its parent directory of the current location and three dots indicate that it is in grandparent directory and so on.

What does from import mean in Python?

Importing refers to allowing a Python file or a Python module to access the script from another Python file or module. You can only use functions and properties your program can access. For instance, if you want to use mathematical functionalities, you must import the math package first.


1 Answers

you need to add from __future__ import absolute_import or use importlib.import_module('c') on Python 2.7

It is default on Python 3.

There was a bug in Python: __future__.py and its documentation claim absolute imports became mandatory in 2.7, but they didn't.

like image 176
jfs Avatar answered Oct 22 '22 07:10

jfs