开发者

python import depth

开发者 https://www.devze.com 2023-01-05 07:41 出处:网络
I\'ve noticed that importing a module will import its functions and methods, and the functions and methods of开发者_JAVA技巧 those as well.Is there a set rule for how many levels down python will impo

I've noticed that importing a module will import its functions and methods, and the functions and methods of开发者_JAVA技巧 those as well. Is there a set rule for how many levels down python will import when you import an upper-level module?

edit

sorry, I think I've been misunderstood by the answers so far responding about multiple imports of some dependencies. I'm thinking of nested folders e.g. in django, if you import django, you can access django.contrib.auth, but you can't access django.contrib.auth.views unless you import that specifically. I was just wondering if it's always two levels down in such a case

second edit

to clarify again.. in the django example, the layout is /django/contrib/auth/views.py, where each of the subfolders has a "init.py" making it a module, none of which define any "all" attributes. Is my example bad, since maybe you can't use the dot syntax to navigate to a file within a module designated folder?


No, python will import what it needs to import. However, each module is only imported once. For example, if one module does import sys and another module does import sys, it will not physically do it twice.


Not really. A module imports stuff from other modules because it needs to use them in that module, otherwise it'll break.


There is no pre-defined import depth level. Import statements are executed, just like any other python statement.

But, you may wonder, how are cycles avoided? Modules are added to sys.modules (i.e., cached) when they get imported for the first time, and that is the first location examined when an import statement is executed. So each module is loaded just once, although it may appear in many import statements.

0

精彩评论

暂无评论...
验证码 换一张
取 消