Forum Archive

Best way to load module from sub directory?

donnieh

Is this the recommended way to load a module from a sub directory?

import imp
a, b ,c = imp.find_module('fruit')
imp.load_module(' ', a, b, c)
import fruit
fruit.apple() 

I have also noticed other examples changing the home directory instead

import sys
sys.path[0:0] = '/folder1'
import fruit
Webmaster4o

I like to put an __init__ file in my folder that imports all the modules in the folder, then use it like a module (from directory import file)

JonB

In the beta, the Documents folder is no longer on the sys.path, nor is '.' so I don't think the init trick works anymore.

The folder that you run a script from gets inserted to the top of sys.path, but I think this might work differently when running from the action menu.

You should probably use sys.path.insert rather than sys.path[0]=, maybe like

if somepath not in sys.path:
    sys.path.insert(somepath,0)
donnieh

Ok cool. I have also been reloading the modules at runtime because they do not reflect my changes unless I kill Pythonista and rerun.

import fruit
fruit = reload(fruit)

Phuket2

If you have the beta, you also have pythonista_startup.py to take some corrective action if you need to.

JonB

This problem will also be corrected in the 2.0 (the beta automatically unloads modules not in site packages, so they get reloaded automatically). Note it is not necessary to have a left hand side to the reload statement

import fruit
reload(fruit)

is sufficient.

Webmaster4o

the __init__ trick works fine in the beta, I use it all the time. Relative imports most certainly do work in the beta, @omz has explained recently that . in sys.path has been replaced by the full path to the directory, which is effectively the same. Although it was removed in one beta, it was put back in, this was a mistake .

JonB

It works in a script - because the absolute path of the script gets added-- but not in the console unless you have run a script there first. sys.path is also reset when you press play or use the action menu.

If mostly you run scripts, from the play button or action menu, you are all good. But this can be confusing when you are debugging in the console, since typed in imports might not work as expected!