1

I am unable to import class from a different file in micro python on raspberry pi pico.

Eg. directory structure

dir/
  |__main.py
  |__imports/
    |_example.py

filename : main.py


from imports.example import ex

a = ex("name")
a.print_name()

filename : example.py


class ex:
    def __init__(self, name):
        self.name = name

    def print_name(self):
        print(self.name)

The error states as following

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ImportError: no module named 'imports.example'

The code works when all the classes are present inside the same file. I am using pico-go vscode extension on debain. I tried adding __ init __.py in the example directory, but no luck.

Marcello Romani
  • 2,967
  • 31
  • 40
vishnu joshi
  • 68
  • 1
  • 9
  • 1
    There's a typo. – Marcello Romani Feb 17 '21 at 10:39
  • 1
    @Marcello Romani Above mentioned code is just an example , just for people to get an idea of the problem and it’s not the actual code. I fixed the typo , thank you for pointing it out. – vishnu joshi Feb 17 '21 at 17:08
  • 1
    I am not certain, but I think only the directories in `sys.path` are searched. Maybe try adding `"imports"` to the `sys.path`? I'm very new at Python + Micropython, so maybe this is incorrect. The MP doc has a section on incompatibilities with standard Python... – aMike Feb 17 '21 at 18:48
  • 1
    @vishnujoshi :-) I didn't mean to be picky (my message didn't convey my intent), what I really meant is that perhaps you overlooked that typo and that's why you got the import error. – Marcello Romani Feb 17 '21 at 20:02

2 Answers2

3

The Run button stands for Run current file. Therefore, only main.py is uploaded. The import will fail because example.py is not uploaded.

Select Pico-Go > Upload Project from All commands for upload example.py to pico. Then click Run and execute main.py, the import will be successful.

Environment

  • vscode (1.65.2)
  • Pico-Go (v1.4.3)
Amamiya
  • 81
  • 4
1

You are missing an empty __init__.py file in the imports directory, which would "magically" (by convention, actually) turn imports into a package.

https://docs.python.org/3.8/tutorial/modules.html#packages

dir/
   main.py
   imports/
        __init__.py     # <= turns 'imports' into a package
        example.py
$ python main.py
name
Marcello Romani
  • 2,967
  • 31
  • 40