%run magic command not working as expected with %python listed first

Ensure that the %run command is the first line in the command cell.

Written by Lucas Ribeiro

Last published at: January 31st, 2025

Problem

When trying to use a %run command, you list it after %python in a notebook as in the following code snippet. You then notice the command behaves unexpectedly or inconsistently. However, when you run notebooks exported in file formats like .py or .ipybn files, they successfully run. 

 

%python
%run
...

 

Cause

The %run command must be the first line in a command cell to execute properly in Databricks notebooks. 

When it is not the first command, and a command like %python is written first, the iPython version of the %run  command is called, leading to the observed different behavior from the Databricks version of this command.

 

Solution

Ensure that the %run command is the first line in the command cell when invoking a notebook from another notebook. 

For more information using %run to import a notebook, review the Orchestrate notebooks and modularize code in notebooks (AWSAzureGCP) documentation.