Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the first argument of the imp.load_source method do?

Tags:

python

module

I'm reading this SO question about importing modules from absolute path. An answer suggest to use following code:

import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

I want to import file from dir which has following structure (it is package):

__int__.py
model_params.py

I've done this:

import01 = imp.load_source('module.name', '/home/wakatana/experiments/model_params/model_params.py')

Now I can access variables within model_params.py via import01.VARIABLE_NAME. It seems like equivalent to import numpy as np. Where model_params.py is like numpy and import01 is like np.

I would like to ask what does the first argument of load_source method do? help(imp) says practically nothing about load_source method, e.g. following help(imp.load_source) returns load_source(...)

Thanks

EDIT based on behzad.nouri comment

On documentation page of load_source is said:

The name argument is used to create or access a module object.

But when I try to access module.name I get an error about not defined module. Also why there is not documentation that can be accessed by help, can I install it somehow? I was hoping that documentation is part of the code itself in python, or is it common practice to not have it built-in but rather have it on-line?

like image 899
Wakan Tanka Avatar asked Aug 02 '15 15:08

Wakan Tanka


1 Answers

The official documentation has a bit more info on the topic.

Basically the name that you load the module with will be used in other files that import that module. Even though no module.name module exists anywhere in the python path, if you load some module and give it that name, other modules that do a regular import with that name will not raise errors and work as expected. Perhaps a small example would illustrate this better:

/tmp/test/foo.py

value = 1337

/tmp/test/bar.py

from foo.bar import value

def print_val():
    print value

/tmp/test/run.py

import imp
foo = imp.load_source('foo.bar', '/tmp/test/foo.py')

import bar

bar.print_val()

As expected, you get 1337 printed to the screen. If the name was not foo.bar, the import would have failed in bar.py since no such module actually exists.

This method can actually be used for monkey patching as it would override imports inside 3rd party modules.

like image 89
Anonymous Avatar answered Oct 03 '22 10:10

Anonymous