Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to alias module name (rename with preserving backward compatibility)

I have a python package named foo, which i use in imports:

import foo.conf
from foo.core import Something

Now i need to rename the foo module into something else, let's say bar, so i want to do:

import bar.conf
from bar.core import Something

but i want to maintain backward compatibility with existing code, so the old (foo.) imports should work as well and do the same as the bar. imports.

How can this be accomplished in python 2.7?

like image 521
Mariusz Jamro Avatar asked Jun 20 '14 08:06

Mariusz Jamro


People also ask

Does Python allows function renaming?

The os. rename() method allows you to rename files in Python.

What is name clash in Python?

Name clashes can occur, for example, if two or more Python modules contain identifiers with the same name and are imported into the same program, as shown below: In this example, module1 and module2 are imported into the same program. Each module contains an identifier named double, which return very different results.

What is import as in Python?

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.


2 Answers

This answer work with submodules:

import sys
import os
from importlib.abc import MetaPathFinder, Loader
import importlib
from MainModule.SubModule import *

class MyLoader(Loader):
    def module_repr(self, module):
        return repr(module)

    def load_module(self, fullname):
        old_name = fullname
        names = fullname.split(".")
        names[1] = "SubModule"
        fullname = ".".join(names)
        module = importlib.import_module(fullname)
        sys.modules[old_name] = module
        return module


class MyImport(MetaPathFinder):
    def find_module(self, fullname, path=None):
        names = fullname.split(".")
        if len(names) >= 2 and names[0] == "Module" and names[1] == "LegacySubModule":
            return MyLoader()


sys.meta_path.append(MyImport())
like image 120
Grzegorz Bokota Avatar answered Nov 06 '22 18:11

Grzegorz Bokota


Do you mean something like this?

import foo as bar

you can use shortcuts for module imports like:

from numpy import array as arr

in: arr([1,2,3])
out: array([1, 2, 3])

and you can also use more than one alias at a time

from numpy import array as foo
in: foo([1,2,3])
out: array([1, 2, 3])

if your foo is a class you can do:

bar=foo()

and call a subfunction of it by:

bar.conf()

Does this help you?

like image 23
www.pieronigro.de Avatar answered Nov 06 '22 19:11

www.pieronigro.de