12

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

2
  • What's the problem with renaming the file? Why won't renaming work? Commented Feb 26, 2009 at 13:25
  • Actually, it was just laziness... I didn't want to remove and add again the file on Launchpad. Commented Feb 26, 2009 at 20:47

8 Answers 8

29

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I can't think of a situation where I'd want to do that, but it's cool that you can :)
One situation: a project where you want compatibility with both python 2.6 and 2.7, but want to use some new 2.7 unittest functionality. This trick allows us to have the code simply use `import unittest' while still using the new functionality, so we didn't need to modify a bunch of import statements everytime when switching python version.
Great. example: import tensorflow.keras as tf_keras import sys sys.modules['tf_keras'] = keras Then you will be able to use keras examples with tensorflow version of keras
I want this to be applied to an example like this: I have a module of pname and developed a modified module of pname_dev. In the running script I want to switch import pname or pname_dev for any situation and the script is using many lines of import pname.util.a, import pname.analysis.run .... Then rather than modifying all the lines of pname, I just want to change the origianal module to pname_orig, then let pname selectively indicate pname_orig or pname_dev. I expect this would work for it.
17

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

import foo as bar
print bar.baz

Comments

10

Yes, you should rename the file. Best would be after you have done that to remove the oldname.pyc and oldname.pyo compiled files (if present) from your system, otherwise the module will be importable under the old name too.

Comments

1

When you do import module_name the Python interpreter looks for a file module_name.extension in PYTHONPATH. So there's no chaging that name without changing name of the file. But of course you can do:

import module_name as new_module_name

or even

import module_name.submodule.subsubmodule as short_name

Useful eg. for writing DB code.

import sqlite3 as sql
sql.whatever..

And then to switch eg. sqlite3 to pysqlite you just change the import line

Comments

0

Every class has an __module__ property, although I believe changing this will not change the namespace of the Class.

If it is possible, it would probably involve using setattr to insert the methods or class into the desired module, although you run the risk of making your code very confusing to your future peers.

Your best bet is to rename the file.

Comments

0

Where would you like to have this __module__ variable, so your original script knows what to import? Modules are recognized by file names and looked in paths defined in sys.path variable.

So, you have to rename the file, then remove the oldname.pyc, just to make sure everything works right.

Comments

0

I had an issue like this with bsddb. I was forced to install the bsddb3 module but hundreds of scripts imported bsddb. Instead of changing the import in all of them, I extracted the bsddb3 egg, and created a soft link in the site-packages directory so that both "bsddb" and "bsddb3" were one in the same to python.

Comments

0

You can set the module via module attribute like below.

func.__module__ = module

You can even create a decorator to change the module names for specific functions in a file for example:

def set_module(module):
    """Decorator for overriding __module__ on a function or class.
    Example usage::
        @set_module('numpy')
        def example():
            pass
        assert example.__module__ == 'numpy'
    """
    def decorator(func):
        if module is not None:
            func.__module__ = module
        return func
    return 

and then use

@set_module('my_module')
def some_func(...):

Pay attention since this decorator is for changing individual module names for functions.

This example is taken from numpy source code: https://github.com/numpy/numpy/blob/0721406ede8b983b8689d8b70556499fc2aea28a/numpy/core/numeric.py#L289

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.