Name FooBar is not defined (import modules)

Hi everyone,

I have in my main python file →

import sqlite3
from MyModule import *



def FooBar():
    with sqlite3.connect('aSQLitedb') as connection....

but I get a

NameError: name ‘sqlite3’ is not defined

Should I import sqlite3 also into MyModule ??


Have you tried it?

Thanks @jamestwebber no, because it not make sense for me…

sqlite3 is define in the main namespace.

and MyModule imported with * , so all from MyModule is loaded in the same namespace…

So, importing again sqlite3 seem not logic… ?

FooBar is executing code in the scope of MyModule, not in the main scope. It doesn’t know what you’ve imported there. It only can see what’s been imported in MyModule.

It would be very hard to understand a program if it all shared the same scope. Imagine if instead of importing sqlite3, your main file had said sqlite3 = 3 (a weird but totally legal thing for it to d). Then FooBar would fail with a strange error when it tried to use an integer as a module. In general, letting all your variables be modified or defined in other modules would be extremely difficult to debug.

It’s really important to learn about scope and namespaces as you learn how to write good code that other people will be able to read and maintain.

Thanks @jamestwebber ,

I was thinking that if we were importing with * then import was acting like a merge… (like if the module code was part of the caller code)

So it seem that’s not the case, and the module stay “independent…”

If someone have a good documentation about this topic I’m all ears. because what I read so far lead me in this reasoning…

This only means that after the MyModule code is loaded in the normal way, instead of creating a MyModule variable in the main module’s global namespace, instead separate variables will be created corresponding to MyModule’s global variables. It has no effect on the process of loading the MyModule module.

The MyModule module should say import sqlite3, because it contains code that uses the sqlite3 module. The point of import is to ensure the availability of things that are used by that code (with the import statement in it). The main module does not need import sqlite3 unless it also directly uses that content.

It “merges”, but with a specific direction, which is the opposite of the direction that would be needed. Stuff is merged from MyModule into the main module.

It is explained in the official documentation:

If the list of identifiers is replaced by a star ('*'), all public names defined in the module are bound in the local namespace for the scope where the import statement occurs.

Names defined in the imported module get bound (assigned) where the import statement is. Not the other way around.

1 Like