in src/smolagents/local_python_executor.py [0:0]
def evaluate_import(expression, state, authorized_imports):
if isinstance(expression, ast.Import):
for alias in expression.names:
if check_import_authorized(alias.name, authorized_imports):
raw_module = import_module(alias.name)
state[alias.asname or alias.name] = get_safe_module(raw_module, authorized_imports)
else:
raise InterpreterError(
f"Import of {alias.name} is not allowed. Authorized imports are: {str(authorized_imports)}"
)
return None
elif isinstance(expression, ast.ImportFrom):
if check_import_authorized(expression.module, authorized_imports):
raw_module = __import__(expression.module, fromlist=[alias.name for alias in expression.names])
module = get_safe_module(raw_module, authorized_imports)
if expression.names[0].name == "*": # Handle "from module import *"
if hasattr(module, "__all__"): # If module has __all__, import only those names
for name in module.__all__:
state[name] = getattr(module, name)
else: # If no __all__, import all public names (those not starting with '_')
for name in dir(module):
if not name.startswith("_"):
state[name] = getattr(module, name)
else: # regular from imports
for alias in expression.names:
if hasattr(module, alias.name):
state[alias.asname or alias.name] = getattr(module, alias.name)
else:
raise InterpreterError(f"Module {expression.module} has no attribute {alias.name}")
else:
raise InterpreterError(
f"Import from {expression.module} is not allowed. Authorized imports are: {str(authorized_imports)}"
)
return None