How to change a Python module name?

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

    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. 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.

提交回复
热议问题