Python as an alias for a module name (renaming while maintaining backward compatibility)

I have a python package with the name foothat I use in the import:

import foo.conf
from foo.core import Something

Now I need to rename the module footo something else, 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.) import should work just like the import bar..

How can this be done in python 2.7?

+6
source share
3 answers

This makes you keep the directory foo, but I think this is the best way to make it work.

Directory setup:

bar
├── __init__.py
└── baz.py
foo
└── __init__.py

foo_bar.py

bar/__init__.py .
bar/baz.py: worked = True

foo/__init__.py:

import sys

# make sure bar is in sys.modules
import bar
# link this module to bar
sys.modules[__name__] = sys.modules['bar']

# Or simply
sys.modules[__name__] = __import__('bar')

foo_bar.py:

import foo.baz

assert(hasattr(foo, 'baz') and hasattr(foo.baz, 'worked'))
assert(foo.baz.worked)

import bar
assert(foo is bar)
+10

- ?

import foo as bar

:

from numpy import array as arr

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

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

foo - , :

bar=foo()

:

bar.conf()

?

+6

This answer works 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())
0
source

Source: https://habr.com/ru/post/1545333/


All Articles