Skip to main content
 首页 » 编程设计

python之如何在不使用 import * 的情况下导入导入其他模块的模块

2024年11月01日9rubylouvre

在父类basehandler.py里面,有几个import语句,一个常量,一个类:

import os 
import sys 
import cgi 
import json 
 
JINJA_ENVIRONMENT = jinja2.Environment(foobar) 
 
class BaseHandler(webapp2.RequestHandler): 
    pass 

另一个模块 main.py 然后使用 from basehandler import * 导入这个父模块

如果我们使用 from basehandler import BaseHandler 或 import basehandler 来避免 from foo import * 语句,那么模块未收到父类导入,程序抛出异常。

如何避免 from foo import *,同时仍然正确导入父模块及其导入的模块?

请您参考如下方法:

then the modules that the parent class imports are not received and the program throws an exception.

如果您的程序使用模块,那么您应该将其导入到模块本身,而不是其他模块中,例如,在您的程序中使用 import os 而不是 from foo import * 其中 foo 模块导入 os inside.


要回答标题中的问题:使所有从另一个模块导入的模块在没有通配符导入的情况下可用:

import inspect  
import foo # your other module 
 
# get all modules from `foo` and make the names available 
globals().update(inspect.getmembers(foo, inspect.ismodule)) #XXX don't do it 

它就像 from foo import * 只导入模块。针对通配符导入的相同警告也适用于此。