← index #7132Issue #2833
Off-topic · high · value 0.442
QUERY · ISSUE

mpy-tool does not properly collect module names for imports

openby matejcikopened 2021-04-19updated 2024-09-13
needs-info

Consider an application that has the following module file:
foo/bar/quux.py

Put an import statement in some other file:

from foo.bar import quux

When freezing the module with mpy-tool.py, the names foo.bar and quux are collected. However:

  • foo.bar.quux is not collected, which will be created as a qstr at runtime, because sys.modules uses it as a key
  • neither foo nor bar is collected. bar will be created as a qstr at runtime, because the dict of foo needs to insert it as a key

Of course, if we use relative imports, there's a similar problem: in foo/bar/baz.py, from . import quux should (but can't really know to) also collect foo.bar.quux despite the string not existing anywhere in the file.

I'm not sure if this is something to solve in mpy-tool itself, or whether there should be a separate step that collects symbols in this way. But it seems that using file names to generate both the fully qualified module name and the individual components would be the right thing to do. (that is basically the workaround i'm using: generate all_modules.py that walk the filesystem and convert every py file name to import that.file.name, which collects "that.file.name", and that.file.name which collects "that"", "file" and "name")

CANDIDATE · ISSUE

exec('import module') doesn't add module to scope when used in imported file

closedby stinosopened 2017-02-01updated 2024-09-30
needs-info

Maybe this is intended or known as a difference with CPython but I looked around and didn't see any documentation related to it.

To reproduce (tested on unix-like ports only): create these 3 files:

foo.py:

foo = 1

bar.py:

def Bar():
  exec('import foo')
  print(foo.foo)

if __name__ == "__main__":
  Bar()

importbar.py:

import bar
bar.Bar()

Running micropython bar.py works ok and prints 1.

Running micropython importbar.py also imports foo but doesn't add it to the scope somehow:

Traceback (most recent call last):
  File "importbar.py", line 2, in <module>
  File "bar.py", line 3, in Bar
NameError: name 'foo' is not defined

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied