Skip to content
Advertisement

Imported package searches for modules in my code

Can someone explain me what is going on here and how to prevent this?

I have a main.py with the following code:

JavaScript

I outsourced some functions into a module named utils.py:

JavaScript

When I run this I get the following output:

JavaScript

So it seems like the torch package I imported has also a utils resource (package) and searches for a module named “utils.dataloaders”. Okay. But why is it searching in my utils module? And why isn’t it continuing searching in its own package if it doesn’t find a matching resource in my code? And last but not least: How can I prevent this situation?

I changed import utils to import utils as ut and call my function with ut.bar() but it doesn’t make any difference.

The only thing that worked is to rename my utils.py to something else but this cannot be the solution…

Thanks for your help. Cheers,

Jan

Advertisement

Answer

The other utils package does not belong to torch, it belongs to the yolov5 repository: /Users/jan/.cache/torch/hub/ultralytics_yolov5_master/utils.

Now, to explain the error: It seems that python would search for sys.modules first when you import utils. If you import your own utils first, it is registered in sys.modules, and python would search in your own utils for things needed for the yolov5 model. Same thing would happen if you create the model first and import your own utils later (at this time, utils of the yolov5 repo is registered in sys.modules, so you won’t be able to import your own utils).

The easiest solution would be to rename your utils.py, or put it under a folder, e.g.,

JavaScript

and import it as

JavaScript

Then, some_name_other_than_utils.utils is registered in sys.modules so it won’t affect importing in yolov5.

Another solution is to copy the yolov5 folder as a subfolder of your project. So everything in the yolov5 folder is under another namespace, without conflicting with your files. But you may need to change some import statements, and replace torch.hub.load with your own model loading function.


In most cases, having utils in your own project shouldn’t conflict with third-party software that also has utils. If you try to import torch and then check sys.modules, you can see torch.utlis, torch.nn.utils, etc., rather than just utils. The following is an example of how this can be done with relative imports:

JavaScript

In some_3rdparty_lib/__init__.py:

JavaScript

Then in main.py:

JavaScript

Note that some_3rdparty_lib does not have to be under your project directory. You can put it anywhere as long as the path is in sys.path. The imported utils would still belong to the namespace some_3rdparty_lib.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement