简体   繁体   English

如何更改 Python 模块名称?

[英]How to change a Python module name?

Is it only possible if I rename the file?是否只能重命名文件? Or is there a __module__ variable to the file to define what's its name?或者文件中有一个__module__变量来定义它的名字吗?

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.如果你真的想用语句 'import newname' 导入文件 'oldname.py',有一个技巧可以使之成为可能:使用旧名称将模块导入某处,然后将其注入到具有新名称的sys.modules . 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 .现在你可以在任何地方使用import newname模块。

You can change the name used for a module when importing by using as:您可以使用 as 更改导入时用于模块的名称:

import foo as bar
print bar.baz

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.最好是在您完成此操作后从系统中删除oldname.pycoldname.pyo编译文件(如果存在),否则该模块也可以以旧名称导入。

When you do import module_name the Python interpreter looks for a file module_name .extension in PYTHONPATH.当您import module_name ,Python 解释器会在 PYTHONPATH 中查找文件module_name .extension 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 sqlite3pysqlite您只需更改导入行

I had an issue like this with bsddb.我在 bsddb 上遇到了这样的问题。 I was forced to install the bsddb3 module but hundreds of scripts imported bsddb.我被迫安装 bsddb3 模块,但数百个脚本导入了 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.我没有更改所有文件中的导入,而是提取了 bsddb3 蛋,并在 site-packages 目录中创建了一个软链接,以便“bsddb”和“bsddb3”与 python 相同。

Every class has an __module__ property, although I believe changing this will not change the namespace of the Class.每个类都有一个__module__属性,尽管我相信改变它不会改变类的命名空间。

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.如果可能的话,它可能涉及使用 setattr 将方法或类插入到所需的模块中,尽管您冒着使您的代码对未来的同行感到非常困惑的风险。

Your best bet is to rename the file.最好的办法是重命名文件。

Where would you like to have this __module__ variable, so your original script knows what to import?您希望将这个__module__变量__module__ ,以便您的原始脚本知道要导入什么? Modules are recognized by file names and looked in paths defined in sys.path variable.模块由文件名识别,并在sys.path变量中定义的路径中sys.path

So, you have to rename the file, then remove the oldname.pyc , just to make sure everything works right.因此,您必须重命名文件,然后删除oldname.pyc ,以确保一切正常。

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此示例取自 numpy 源代码: https : //github.com/numpy/numpy/blob/0721406ede8b983b8689d8b70556499fc2aea28a/numpy/core/numeric.py#L289

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM