Page 1 of 1

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

Posted: Mon Aug 06, 2018 5:29 pm
by pmulvey
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??

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

Posted: Thu Aug 09, 2018 4:25 am
by liudr
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.

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

Posted: Thu Aug 09, 2018 7:41 am
by Christian Walther
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.