Is this __import__ function correct?

I have a package called jiva_tasks that I am trying to import via celery (using the CELERY_IMPORTS celeryconfig attribute). The import operation used by celery is as follows:

 __import__(module, [], [], ['']) 

Oddly enough, when this syntax is used, the module receives the import twice, once as jiva_tasks and another time as jiva_tasks. (with a period at the end). Now there are good chances that celery should be held in globals, and not in an empty list, but this seems to me broken. It seems strange that even if incorrect arguments are given, __import__ will import something that is not a valid python module name.

I know that the way to fix this is to go to globals , but I want to understand why I get this result. Is this a mistake or is there something I don’t understand about how __import__ works?

Update : it also works fine if I use importlib .

Update 2 . Here sys.meta_path and sys.import_path right before the __import__ line:

 >>> sys.meta_path [] >>> sys.path_hooks [<type 'zipimport.zipimporter'>] 

It does not seem to me that there is anything unusual. However, I only now realized that the package I import is installed using the setuptools development team. Does it matter?

+4
source share
1 answer

Create an empty file "foo.py" and then create "bar.py" which says:

 __import__('foo', [], [], ['']) import sys print sorted(sys.modules) 

prints a list containing only foo once, not foo. or anything else with an endpoint - so it's not just the fact that celery uses __import__ , which causes the problem here. Can you figure out what an extra celery step does that the second module adds? (Or print sorted(sys.modules) immediately before and after calling __import__() assumes that both modules appear at that moment - in this case, we need to see which import hooks are defined at the time of import?)

+1
source

Source: https://habr.com/ru/post/1312474/


All Articles