Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I change the order where python looks for a module first?

Tags:

python

import

Imagine I have a script, let's say my_tools.py that I import as a module. But my_tools.py is saved twice: at C:\Python27\Lib and at the same directory from where the script is run that does the import.

Can I change the order where python looks for my_tools.py first? That is, to check first if it exists at C:\Python27\Lib and if so, do the import?

like image 616
LarsVegas Avatar asked Oct 26 '12 07:10

LarsVegas


2 Answers

You can manipulate sys.path as much as you want... If you wanted to move the current directory to be scanned last, then just do sys.path[1:] + sys.path[:1]. Otherwise, if you want to get into the nitty gritty then the imp module can be used to customise until your hearts content - there's an example on that page, and one at http://blog.dowski.com/2008/07/31/customizing-the-python-import-system/

like image 94
Jon Clements Avatar answered Nov 01 '22 17:11

Jon Clements


You can modify sys.path, which will determine the order and locations that Python searches for imports. (Note that you must do this before the import statement.)

like image 25
Amber Avatar answered Nov 01 '22 17:11

Amber