How to change a Python module name?

后端 未结 7 688
暗喜
暗喜 2021-01-02 23:56

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

相关标签:
7条回答
  • 2021-01-03 00:24

    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.

    0 讨论(0)
  • 2021-01-03 00:35

    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.

    0 讨论(0)
  • 2021-01-03 00:39

    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.

    0 讨论(0)
  • 2021-01-03 00:40

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

    import foo as bar
    print bar.baz
    
    0 讨论(0)
  • 2021-01-03 00:41

    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.

    0 讨论(0)
  • 2021-01-03 00:43

    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

    0 讨论(0)
提交回复
热议问题