Mixing of imports and statements ok or not?

I just learned from the tutorial video that we should avoid mixing imports and any other Python statements.

But then I see in nbdev/shortcuts this:

So function definitions are still okay in a cell with all the imports?

Cells are only executed when rendered by nbdev+quarto if they have an import, or if they are exported. Therefore, the cells in your notebook that have either of these features must be able to run successfully, even when previous cells (which aren’t exported or don’t have import) have not been run.

Since the cell you show above is exported, it’s going to be run anyway. And everything in it can run successfully without any previous cells being run.

3 Likes

Now I get it…


Which comes from nbdev - Docs Website

The key is

all the code in that cell (the cell with imports) will be executed every time you build your docs (even if it doesn’t have an #| export).

I came again to look at this because I just noticed a module that was not raising errors despite I had imports mixed with normal code.

I guess… to be safe, separate them.