Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a Python module name?

Tags:

python

module

Is it only possible if I rename the file? Or is there a __module__ variable to the file to define what's its name?

like image 847
Rodrigo Avatar asked Feb 26 '09 12:02

Rodrigo


2 Answers

You can change the name used for a module when importing by using as:

import foo as bar
print bar.baz
like image 59
Ignacio Vazquez-Abrams Avatar answered Oct 12 '22 02:10

Ignacio Vazquez-Abrams


If you really want to import the file 'oldname.py' with the statement 'import newname', there is a trick that makes it possible: Import the module somewhere with the old name, then inject it into sys.modules with the new name. Subsequent import statements will also find it under the new name. Code sample:

# this is in file 'oldname.py'
...module code...

Usage:

# inject the 'oldname' module with a new name
import oldname
import sys
sys.modules['newname'] = oldname

Now you can everywhere your module with import newname.

like image 29
theller Avatar answered Oct 12 '22 02:10

theller