为什么这不起作用:
>>> import structlog
>>> structlog.contextvars.bind_contextvars()
AttributeError: module 'structlog' has no attribute 'contextvars'
>>>但这确实是:
>>> from structlog.contextvars import bind_contextvars
>>> bind_contextvars()
>>>似乎找不到关于何时使用from x import y vs import x的文档。
发布于 2021-05-07 23:58:10
我想知道您使用的是哪个版本的库和Python,因为在Python3.8(Win10 x64)和structlog 21.1.0 (最新版本)中,我看不到错误,并且作为code indicates (包的__init__.py),子模块被导入(因为contextvars.py存在):
try:
from structlog import contextvars
except ImportError:
contextvars = None # type: ignore在一些较旧的版本中,它可能会有所不同,子模块可能只在某些情况下被导入,当不导入时会导致错误。
发布于 2021-05-08 00:07:15
虽然我无法在单独的环境中复制此问题...
~/GivingCaringSolution$ python
Python 3.8.9 (default, May 3 2021, 02:40:41)
[GCC 7.5.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import structlog
>>> structlog.contextvars.bind_contextvars()
>>> ...the一般的答案是,此行为取决于特定库是如何构造的,以及是否在导入主模块时解析并添加了所有子模块(或您试图使用的子模块,如contextvars ),并将其添加为导入模块(如structlog)的成员。
这里的实际使用文档是给定模块的维护者提供的官方文档(如果有)。它的质量,以及如何导入的指导量,自然会因作者和模块而异。
在这种特殊情况下,official structlog documentation about its context variables module将是一个很好的起点。
https://stackoverflow.com/questions/67437871
复制相似问题