本文整理匯總了Python中warnings.WarningMessage方法的典型用法代碼示例。如果您正苦於以下問題:Python warnings.WarningMessage方法的具體用法?Python warnings.WarningMessage怎麽用?Python warnings.WarningMessage使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類warnings
的用法示例。
在下文中一共展示了warnings.WarningMessage方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __enter__
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def __enter__(self, *args, **kwargs):
rv = super(WarningTestMixin._AssertWarnsContext, self).__enter__(*args, **kwargs)
if self._showwarning is not self._module.showwarning:
super_showwarning = self._module.showwarning
else:
super_showwarning = None
def showwarning(*args, **kwargs):
if super_showwarning is not None:
super_showwarning(*args, **kwargs)
self._warning_log.append(warnings.WarningMessage(*args, **kwargs))
self._module.showwarning = showwarning
return rv
示例2: _add_l1_l2_regularization
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def _add_l1_l2_regularization(self, core_network):
if self.l1_reg > 0 or self.l2_reg > 0:
# weight norm should not be combined with l1 / l2 regularization
if self.weight_normalization is True:
warnings.WarningMessage("l1 / l2 regularization has no effect when weigh normalization is used")
weight_vector = tf.concat(
[tf.reshape(param, (-1,)) for param in core_network.get_params_internal() if '/W' in param.name],
axis=0)
if self.l2_reg > 0:
self.l2_reg_loss = self.l2_reg * tf.reduce_sum(weight_vector ** 2)
tf.losses.add_loss(self.l2_reg_loss, tf.GraphKeys.REGULARIZATION_LOSSES)
if self.l1_reg > 0:
self.l1_reg_loss = self.l1_reg * tf.reduce_sum(tf.abs(weight_vector))
tf.losses.add_loss(self.l1_reg_loss, tf.GraphKeys.REGULARIZATION_LOSSES)
示例3: __enter__
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def __enter__(self):
clean_warning_registry() # be safe and not propagate state + chaos
warnings.simplefilter('always')
if self._entered:
raise RuntimeError("Cannot enter %r twice" % self)
self._entered = True
self._filters = self._module.filters
self._module.filters = self._filters[:]
self._showwarning = self._module.showwarning
if self._record:
self.log = []
def showwarning(*args, **kwargs):
self.log.append(warnings.WarningMessage(*args, **kwargs))
self._module.showwarning = showwarning
return self.log
else:
return None
示例4: warning_record_to_str
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def warning_record_to_str(warning_message):
"""Convert a warnings.WarningMessage to a string."""
warn_msg = warning_message.message
msg = warnings.formatwarning(
warn_msg,
warning_message.category,
warning_message.filename,
warning_message.lineno,
warning_message.line,
)
return msg
示例5: pytest_warning_captured
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def pytest_warning_captured(
warning_message: "warnings.WarningMessage",
when: "Literal['config', 'collect', 'runtest']",
item: Optional["Item"],
location: Optional[Tuple[str, int, str]],
) -> None:
"""(**Deprecated**) Process a warning captured by the internal pytest warnings plugin.
.. deprecated:: 6.0
This hook is considered deprecated and will be removed in a future pytest version.
Use :func:`pytest_warning_recorded` instead.
:param warnings.WarningMessage warning_message:
The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains
the same attributes as the parameters of :py:func:`warnings.showwarning`.
:param str when:
Indicates when the warning was captured. Possible values:
* ``"config"``: during pytest configuration/initialization stage.
* ``"collect"``: during test collection.
* ``"runtest"``: during test execution.
:param pytest.Item|None item:
The item being executed if ``when`` is ``"runtest"``, otherwise ``None``.
:param tuple location:
When available, holds information about the execution context of the captured
warning (filename, linenumber, function). ``function`` evaluates to <module>
when the execution context is at the module level.
"""
示例6: pytest_warning_recorded
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def pytest_warning_recorded(
warning_message: "warnings.WarningMessage",
when: "Literal['config', 'collect', 'runtest']",
nodeid: str,
location: Optional[Tuple[str, int, str]],
) -> None:
"""
Process a warning captured by the internal pytest warnings plugin.
:param warnings.WarningMessage warning_message:
The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains
the same attributes as the parameters of :py:func:`warnings.showwarning`.
:param str when:
Indicates when the warning was captured. Possible values:
* ``"config"``: during pytest configuration/initialization stage.
* ``"collect"``: during test collection.
* ``"runtest"``: during test execution.
:param str nodeid: full id of the item
:param tuple|None location:
When available, holds information about the execution context of the captured
warning (filename, linenumber, function). ``function`` evaluates to <module>
when the execution context is at the module level.
.. versionadded:: 6.0
"""
# -------------------------------------------------------------------------
# error handling and internal debugging hooks
# -------------------------------------------------------------------------
示例7: pytest_warning_recorded
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def pytest_warning_recorded(
self, warning_message: warnings.WarningMessage, nodeid: str,
) -> None:
from _pytest.warnings import warning_record_to_str
fslocation = warning_message.filename, warning_message.lineno
message = warning_record_to_str(warning_message)
warning_report = WarningReport(
fslocation=fslocation, message=message, nodeid=nodeid
)
self._add_stats("warnings", [warning_report])
示例8: warning_record_to_str
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def warning_record_to_str(warning_message: warnings.WarningMessage) -> str:
"""Convert a warnings.WarningMessage to a string."""
warn_msg = warning_message.message
msg = warnings.formatwarning(
str(warn_msg),
warning_message.category,
warning_message.filename,
warning_message.lineno,
warning_message.line,
)
return msg
示例9: deprecated_call
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def deprecated_call( # noqa: F811
func: Optional[Callable] = None, *args: Any, **kwargs: Any
) -> Union["WarningsRecorder", Any]:
"""Assert that code produces a ``DeprecationWarning`` or ``PendingDeprecationWarning``.
This function can be used as a context manager::
>>> import warnings
>>> def api_call_v2():
... warnings.warn('use v3 of this api', DeprecationWarning)
... return 200
>>> with deprecated_call():
... assert api_call_v2() == 200
It can also be used by passing a function and ``*args`` and ``**kwargs``,
in which case it will ensure calling ``func(*args, **kwargs)`` produces one of
the warnings types above. The return value is the return value of the function.
In the context manager form you may use the keyword argument ``match`` to assert
that the warning matches a text or regex.
The context manager produces a list of :class:`warnings.WarningMessage` objects,
one for each warning raised.
"""
__tracebackhide__ = True
if func is not None:
args = (func,) + args
return warns((DeprecationWarning, PendingDeprecationWarning), *args, **kwargs)
示例10: __init__
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def __init__(self) -> None:
# Type ignored due to the way typeshed handles warnings.catch_warnings.
super().__init__(record=True) # type: ignore[call-arg] # noqa: F821
self._entered = False
self._list = [] # type: List[warnings.WarningMessage]
示例11: list
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def list(self) -> List["warnings.WarningMessage"]:
"""The list of recorded warnings."""
return self._list
示例12: __getitem__
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def __getitem__(self, i: int) -> "warnings.WarningMessage":
"""Get a recorded warning by index."""
return self._list[i]
示例13: __iter__
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def __iter__(self) -> Iterator["warnings.WarningMessage"]:
"""Iterate through the recorded warnings."""
return iter(self._list)
示例14: pop
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def pop(self, cls: "Type[Warning]" = Warning) -> "warnings.WarningMessage":
"""Pop the first recorded warning, raise exception if not exists."""
for i, w in enumerate(self._list):
if issubclass(w.category, cls):
return self._list.pop(i)
__tracebackhide__ = True
raise AssertionError("%r not found in warning list" % cls)
示例15: unserialize_warning_message
# 需要導入模塊: import warnings [as 別名]
# 或者: from warnings import WarningMessage [as 別名]
def unserialize_warning_message(data):
import warnings
import importlib
if data["message_module"]:
mod = importlib.import_module(data["message_module"])
cls = getattr(mod, data["message_class_name"])
message = None
if data["message_args"] is not None:
try:
message = cls(*data["message_args"])
except TypeError:
pass
if message is None:
# could not recreate the original warning instance;
# create a generic Warning instance with the original
# message at least
message_text = "{mod}.{cls}: {msg}".format(
mod=data["message_module"],
cls=data["message_class_name"],
msg=data["message_str"],
)
message = Warning(message_text)
else:
message = data["message_str"]
if data["category_module"]:
mod = importlib.import_module(data["category_module"])
category = getattr(mod, data["category_class_name"])
else:
category = None
kwargs = {"message": message, "category": category}
# access private _WARNING_DETAILS because the attributes vary between Python versions
for attr_name in warnings.WarningMessage._WARNING_DETAILS:
if attr_name in ("message", "category"):
continue
kwargs[attr_name] = data[attr_name]
return warnings.WarningMessage(**kwargs)