Dealing with module name collision

南笙酒味 提交于 2021-02-08 15:18:38

问题


Occasionally, module name collisions happen between the application and an internal file in a third-party package. For example, a file named profile.py in the current folder will cause jupyter notebook to crash as it attempts to import it instead of its own profile.py. What's a good way to avoid this problem, from the perspective of the package user? (Or is this something that the package developer should somehow prevent?)

Note: while a similar problem occurs due to a collision between application and built-in names (e.g., time.py or socket.py), at least it's relatively easy to remember the names of standard library modules and other built-in objects.


回答1:


The current directory is the directory which contains the main script of the application. If you want to avoid name collisions in this directory, don't put any modules in it.

Instead, use a namespace. Create a uniquely-named package in the directory of the main script, and import everything from that. The main script should be very simple, and contain nothing more than this:

if __name__ == '__main__':

    from mypackage import myapp

    myapp.run()

All the modules inside the package should also use from imports to access the other modules within the package. For example, myapp.py might contain:

from mypackage import profile


来源:https://stackoverflow.com/questions/40210574/dealing-with-module-name-collision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!