How exactly does import work (like #include??)

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
pmulvey
Posts: 45
Joined: Sun Jul 29, 2018 8:12 am
Location: Athlone, Ireland

How exactly does import work (like #include??)

Post by pmulvey » Mon Aug 06, 2018 5:29 pm

It would appear that import does not work like the include directive which instructs the compiler to insert the file at that point in the code. I have a module with my own library functions that is growing and I want to have just a small development module with the function that I am currently developing (for fast downloads). My main.py imports the main library module so I tried importing the small testing module there after the main library module. However REPL tells me that for instance "NameError: name 'lcd' is not defined" even though the library module has this definition and other functions in that module are using it. So what's the story with imports??

User avatar
liudr
Posts: 211
Joined: Tue Oct 17, 2017 5:18 am

Re: How exactly does import work (like #include??)

Post by liudr » Thu Aug 09, 2018 4:25 am

I'm learning Python myself, with a C background. I would recommend you to do a skeletal module and main.py to investigate and learn. From what I read on a python book, import executes all code in the imported library and adds the imported code's name space to the current name space. Say you:
import doit

Then any variables or functions within doit.py enter the current name space such as doit.do_this() or doit.status. I bet, without code or a skeletal structure demonstrating your issues, you will not get a lot of help.

Christian Walther
Posts: 169
Joined: Fri Aug 19, 2016 11:55 am

Re: How exactly does import work (like #include??)

Post by Christian Walther » Thu Aug 09, 2018 7:41 am

I suspect the reason why you are not getting more help is that this is not MicroPython-specific, and is not a particularly appealing question to answer because it can easily be answered by reading documentation: Reference, Tutorial.

Short answer: Yes, import does not work like #include. liudr’s response has the main point, but do read the documentation to get the whole picture.

Post Reply