Relative import statements

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
User avatar
iggy12345
Posts: 2
Joined: Sat Aug 01, 2020 3:27 pm

Relative import statements

Post by iggy12345 » Mon Sep 07, 2020 12:43 am

I don't know if this has already been brought up, but I've been working on creating a tool to flash my esp projects to my microcontroller, and I just realized that there are no relative imports in micropython. It would seem that micropython treats all import statements as absolute from the root directory, and not from the directory that the file is located, for example:

If I have a project set up like this:

Code: Select all

myproj
|-> main.py
|-> libs
    |-> display.py
    |-> ssd1306.py
Then in display when I want to use the ssd1306.py I have to do an absolute import like:

Code: Select all

import libs.ssd1306
instead of

Code: Select all

import ssd1306
# or
import .ssd1306
like I would normally.

Is there plans to implement something like this in the future? I'm planning on sharing my project deployment script, and and knowing the answer will determine how much of an overhaul I'll need to do.

User avatar
pythoncoder
Posts: 4917
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Relative import statements

Post by pythoncoder » Mon Sep 07, 2020 6:09 am

I'm not entirely sure of the issue here. I recreated your directory structure with display.py being

Code: Select all

from . import ssd1306
ssd1306.py simply contained a print statement. Running MicroPython from the myproj directory I issued

Code: Select all

>>> import libs.display
and the print statement ran (both in MicroPython and CPython).

Your syntax

Code: Select all

import .ssd1306
causes a syntax error, both in MicroPython and in CPython V3.6.9. So it seems MicroPython's behaviour is correct.
Peter Hinch

Post Reply