Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with module name collision

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.

like image 463
max Avatar asked Oct 29 '22 18:10

max


1 Answers

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
like image 104
ekhumoro Avatar answered Nov 13 '22 17:11

ekhumoro