6.9. Importing modules

The standard way in Python to import modules in a script is to use the import keyword. The interpreter searches in a list of directories for a module with the specified name and, if found, adds the module name in the script namespace

This works fine on a mono-user, mono-process environment, but causes problems if several users can interact with the interpreter at the same time. Each of them can modify the list of directories to search in, and if 2 users want to import modules with the same name, the interpreter might return user A's module to user B

To import modules safely in Karrigell, here is what you should do :

  • if the module is in your standard Python distribution, or has been installed by the setup tools, just use the usual import keyword : there is no risk of confusion
  • you can store your own modules in the package directory of your Karrigell distribution, and import them with import
  • for user-defined modules inside your application, use the built-in function Import(module_url[,**kw])
This function Import() returns an object which will behave like an imported module. To use it in the script you must give a name to this object :
foo = Import("foo.py")

The equivalent of from foo import bar is :

bar = Import("foo.py").bar

Note that there is no equivalent of from foo import *

The url of the imported module is resolved like the scripts url, so you don't have to specify the extension : foo = Import("foo") works

Imported scripts are run in a namespace which includes some of the built-in names defined in the "importer" script (CONFIG, _(), Import(), PRINT()) but not the names which are related to the importer folder, because the imported script can be in another folder. If you want CWD or REL to be available in the imported script, you must pass them explicitely as arguments to Import() :

foo = Import("foo",REL=REL) 

In foo.py the name REL will be available :

import os
content = open(REL("data.txt"))

More generally, you can pass keyword parameters to the Import() function if you need them in the imported script