简体   繁体   English

导入中的python导入

[英]python import within import

i am trying to import a module within a module and then access the lower level module from the top, however it is not available. 我正在尝试导入模块中的模块,然后从顶部访问较低级别的模块,但它不可用。 is this normal behaviour? 这是正常的行为吗?

# caller.py
import first
print second.some_var

# first.py
import second

# second.py
some_var = 1

running caller.py gives error 运行caller.py会出错

NameError: name 'second' is not defined

do i have to import second within caller.py ? 我是否必须在caller.py import second this seems counter-intuitive to me. 这对我来说似乎是违反直觉的。

You can use 您可以使用

import first
print first.second.some_var

Having second appear in the namespace automatically just by importing first would lead to lots of conflicts 只有通过first导入才会自动在名称空间中出现second会导致很多冲突

This would also work 这也行得通

from first import second
print second.some_var

The use of wildcard 使用通配符

from first import *

is discouraged because if someone adds extra attributes/functions to first they may overwrite attributes you are using locally if they happen to choose the same name 气馁,因为如果有人添加了一些额外的属性/功能, first ,他们可能会,如果他们碰巧选择了相同的名字覆盖使用的是本地属性

import first will import the name first into the global namespace, but it does not import everything from first into the namespace. import first将导入的名字first进入全局命名空间,但它不会从导入所有first进入的命名空间。 So you can do one of the following: 因此,您可以执行以下操作之一:

  • Access second through first : 进入second通过first

     import first print first.second.some_var 
  • Import second directly into the namespace of caller.py: 导入second直接进入caller.py的命名空间:

     from first import second print second.some_var 

Note that you can use from first import * to import all of the names from first into the namespace, but this is generally discouraged. 请注意,您可以使用from first import *将所有名称从first导入到命名空间,但通常不鼓励这样做。

instead use: 改为使用:

from first import second
print first.second.some_var

It is a lot more compressed too. 它压缩得更多。 Why are you doing your way anyway? 你为什么要按自己的方式行事呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM