Skip to content

Commit f502fe8

Browse files
committed
support "from module import *"
1 parent d7e9dfe commit f502fe8

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

custom_components/pyscript/eval.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -412,9 +412,14 @@ async def ast_importfrom(self, arg):
412412
else:
413413
mod = sys.modules[arg.module]
414414
for imp in arg.names:
415-
self.sym_table[imp.name if imp.asname is None else imp.asname] = getattr(
416-
mod, imp.name
417-
)
415+
if imp.name == "*":
416+
for name, value in mod.__dict__.items():
417+
if name[0] != "_":
418+
self.sym_table[name] = value
419+
else:
420+
self.sym_table[
421+
imp.name if imp.asname is None else imp.asname
422+
] = getattr(mod, imp.name)
418423

419424
async def ast_if(self, arg):
420425
"""Execute if statement."""
@@ -604,7 +609,7 @@ async def recurse_assign(self, lhs, val):
604609
try:
605610
val_iter = val.__iter__()
606611
except AttributeError:
607-
raise TypeError("cannot unpack non-iterable object")
612+
raise TypeError("cannot unpack non-iterable object")
608613
sentinel = object()
609614
for lhs_elt in lhs.elts:
610615
val_elt = next(val_iter, sentinel)
@@ -614,7 +619,7 @@ async def recurse_assign(self, lhs, val):
614619
)
615620
await self.recurse_assign(lhs_elt, val_elt)
616621
if next(val_iter, sentinel) is not sentinel:
617-
raise TypeError(f"too many values to unpack (expected {len(lhs.elts)})")
622+
raise TypeError(f"too many values to unpack (expected {len(lhs.elts)})")
618623
elif isinstance(lhs, ast.Subscript):
619624
var = await self.aeval(lhs.value)
620625
if isinstance(lhs.slice, ast.Index):

tests/custom_components/pyscript/test_unit_eval.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,14 @@
185185
["import random as rand, math as m\n[rand.uniform(10,10), m.sqrt(1024)]", [10, 32]],
186186
["import cmath\ncmath.sqrt(complex(3, 4))", 2 + 1j],
187187
["from math import sqrt as sqroot\nsqroot(1024)", 32],
188+
["from math import sin, cos, sqrt\nsqrt(1024)", 32],
189+
["from math import *\nsqrt(1024)", 32],
190+
["from math import sin, floor, sqrt; [sqrt(9), floor(10.5)]", [3, 10]],
191+
["from math import *; [sqrt(9), floor(10.5)]", [3, 10]],
192+
[
193+
"from math import floor as floor_alt, sqrt as sqrt_alt; [sqrt_alt(9), floor_alt(10.5)]",
194+
[3, 10],
195+
],
188196
["[i for i in range(7) if i != 5 if i != 3]", [0, 1, 2, 4, 6]],
189197
[
190198
"""

0 commit comments

Comments
 (0)