是否“从 - 进口”执行整个模块? [英] Does "from-import" exec the whole module?

查看:98
本文介绍了是否“从 - 进口”执行整个模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我知道 from-import import 完全相同,除了它是显然不是因为命名空间的填充方式不同。

OK, so I know that from-import is "exactly" the same as import, except that it's obviously not because namespaces are populated differently.

我的问题主要是因为我有一个 utils 模块,其中有一个或者我的应用程序中的每个其他模块使用的两个函数,我正在努力合并标准库 logging 模块,据我所知,我需要像这样做:

My question is primarily motivated because I have a utils module which has one or two functions that are used by every other module in my app, and I'm working on incorporating the standard library logging module, which as far as I can tell I need to do sorta like this:

import logging
logging.basicConfig(filename="/var/log")  # I want file logging

baselogger = logging.getLogger("mine")
#do some customizations to baselogger

然后在另一个模块中使用它我会再次导入日志记录:

and then to use it in a different module I would import logging again:

import logging
logger = logging.getlogger("mine")

# log stuff

但我想知道的是,如果我从utils import awe做 some_func 我的记录器肯定会被设置,记录模块会按照我想要的方式设置吗?

But what I want to know is if I do a from utils import awesome_func will my logger definitely be set up, and will the logging module be set up the way I want?

这也适用于其他通用设置。

This would apply to other generic set-ups as well.

推荐答案

<看起来好像答案是肯定的:

Looks like like the answer is yes:

$ echo 'print "test"
def f1():
    print "f1"

def f2():
    print "f2"

' > util.py

$ echo 'from util import f1
f1()
from util import f2
f2()
' > test.py

$ python test.py 
test
f1
f2

$ 

这篇关于是否“从 - 进口”执行整个模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆