How to change a Python module name?

后端 未结 7 719
暗喜
暗喜 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: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

提交回复
热议问题