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?
The os. rename() method allows you to rename files 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.
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.
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())
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With