Global and dynamic imports
I've seen a complaint the other day that you cannot do something like this in marimo.
from math import *
You get a big red error message when you try this because marimo cares about what global variables are around. Without know this for sure it has a terrible time understanding in what order cells need to run and all the benefits of a reactive environment are lost.
So we can't import like this ... can we?
Python is super dynamic though!
It's definately true that it is discouraged, but technically it is not impossible. You could do this:
def load_globals(module_name):
"""
Import all attributes from a module into the global namespace,
respecting the module's __all__ attribute if it exists.
Similar to 'from module import *' but in a way that Marimo can track.
"""
import importlib
module = importlib.import_module(module_name)
# Check if the module defines __all__
if hasattr(module, '__all__'):
# Use the names defined in __all__
names_to_import = module.__all__
else:
# Fall back to all public attributes (those not starting with '_')
names_to_import = [name for name in dir(module) if not name.startswith('_')]
# Add each attribute to the global namespace
for name in names_to_import:
if hasattr(module, name): # Ensure the attribute exists
globals()[name] = getattr(module, name)
else:
print(f"Warning: {module_name} declares '{name}' in __all__ but it doesn't exist")
return names_to_import # Return list of imported names for reference
load_globals("math");
# I have a variable available with an import statement!
pi
This will allow you to load everything in one swoop but (!) you will enter dangerous territory when you do this. In this case marimo will not be able to detect the imports as global variables anymore and that also means it cannot understand the order of the cells anymore. It simply cannot be inferred from the variable declarations by looking at the code. You effectively omit the safety mechanism entirely when you do this. You could even override pi this way, while you'd normally get an error.
I wrote this to celebrate the dynamic nature of Python. If there is a will, there usually really is a way. But there are consequences to pulling tricks like this in a notebook environment that's build on reactivity. More details on the behavior in marimo can be found here.