{"record":{"id":"1ff0c00c5d4c2759","repo":"python/cpython","slug":"warnings-showwarning-must-be-set-to-a-function-o","errorCode":null,"errorMessage":"warnings.showwarning() must be set to a function or method","messagePattern":"warnings\\.showwarning\\(\\) must be set to a function or method","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"Lib/_py_warnings.py","lineNumber":227,"sourceCode":"                  f'allocation traceback\\n')\n    return s\n\n\n# Keep a reference to check if the function was replaced\n_showwarning_orig = showwarning\n\n\ndef _showwarnmsg(msg):\n    \"\"\"Hook to write a warning to a file; replace if you like.\"\"\"\n    try:\n        sw = _wm.showwarning\n    except AttributeError:\n        pass\n    else:\n        if sw is not _showwarning_orig:\n            # warnings.showwarning() was replaced\n            if not callable(sw):\n                raise TypeError(\"warnings.showwarning() must be set to a \"\n                                \"function or method\")\n\n            sw(msg.message, msg.category, msg.filename, msg.lineno,\n               msg.file, msg.line)\n            return\n    _wm._showwarnmsg_impl(msg)\n\n\n# Keep a reference to check if the function was replaced\n_formatwarning_orig = formatwarning\n\n\ndef _formatwarnmsg(msg):\n    \"\"\"Function to format a warning the standard way.\"\"\"\n    try:\n        fw = _wm.formatwarning\n    except AttributeError:\n        pass","sourceCodeStart":209,"sourceCodeEnd":245,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/_py_warnings.py#L209-L245","documentation":"Raised by warnings._showwarnmsg when a warning is actually emitted and the hook machinery notices that warnings.showwarning has been replaced with something non-callable. The module deliberately validates user overrides before dispatching, so assigning a constant, string, or None to warnings.showwarning turns the next displayed warning into TypeError.","triggerScenarios":"Assigning a non-callable to warnings.showwarning (e.g. `warnings.showwarning = None` to 'silence' warnings, or assigning a string/template) and then any code path triggers a warning that reaches the display hook.","commonSituations":"Attempts to mute warnings by clobbering showwarning; copy/pasted snippets that assign a log-format string; libraries that save/restore the hook incorrectly and restore None; test teardowns that reset attributes indiscriminately.","solutions":["To silence warnings use the filter API instead: warnings.simplefilter('ignore') or filterwarnings","If replacing the hook, assign a callable with the (message, category, filename, lineno, file=None, line=None) signature","Restore the original by deleting your override or reassigning a proper function rather than None"],"exampleFix":"# before\nimport warnings\nwarnings.showwarning = None      # next warning -> TypeError\n\n# after\nwarnings.simplefilter('ignore')   # correct way to silence\n# or a real hook:\nwarnings.showwarning = lambda message, category, filename, lineno, file=None, line=None: print(f'{filename}:{lineno}: {message}')","handlingStrategy":"validation","validationCode":"import warnings\n\ndef set_warning_hook(fn) -> None:\n    if not callable(fn):\n        raise TypeError(f'showwarning must be callable, got {fn!r}')\n    warnings.showwarning = fn","typeGuard":"def is_valid_hook(fn) -> bool:\n    import inspect\n    return callable(fn) and len(inspect.signature(fn).parameters) >= 4","tryCatchPattern":"try:\n    warnings.warn('something')\nexcept TypeError as e:\n    if 'showwarning() must be set' in str(e):\n        import warnings\n        del warnings.showwarning  # drop the bad override, restore default\n        warnings.warn('something')\n    else:\n        raise","preventionTips":["Never silence warnings by assigning to warnings.showwarning; use simplefilter('ignore')","If you replace the hook, replace it with a function and restore it in a finally block","Use warnings.catch_warnings() to scope hook changes instead of global assignment"],"tags":["warnings","hook","configuration"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}