### Python: Raise ValueError with Custom Theme Source: https://context7.com/qix-/better-exceptions/llms.txt Demonstrates raising a ValueError with a custom theme. This basic example shows the fundamental usage of raising an exception. ```python def test(): value = "custom theme" raise ValueError("Testing custom colors") test() ``` -------------------------------- ### Manual Exception Hook Installation (Python) Source: https://context7.com/qix-/better-exceptions/llms.txt Programmatically install the exception handler in your Python application. This ensures that all subsequent exceptions will be formatted with enhanced details. ```python import better_exceptions better_exceptions.hook() # Now all exceptions will be formatted foo = 52 bar = foo - 50 def divide(a, b): result = a / b return result # This will show variable values when exception occurs divide(10, 0) # ZeroDivisionError with variable inspection ``` -------------------------------- ### Automatic Global Exception Hook Installation (Bash) Source: https://context7.com/qix-/better-exceptions/llms.txt Enable better-exceptions globally by setting an environment variable. The library will automatically install its exception handler when Python starts. ```bash # Linux/macOS export BETTER_EXCEPTIONS=1 python script.py # Windows setx BETTER_EXCEPTIONS 1 python script.py ``` -------------------------------- ### Install better-exceptions Source: https://github.com/qix-/better-exceptions/blob/master/README.md Install the better-exceptions package using pip. This is the primary step to enable the library's functionality. ```console pip install better_exceptions ``` -------------------------------- ### Programmatic Enhanced REPL Start (Python) Source: https://context7.com/qix-/better-exceptions/llms.txt Launch an interactive Python console programmatically using the `interact` function from the `better_exceptions` library. This allows for embedding an enhanced REPL within scripts or applications. ```python from better_exceptions import interact # Launch interactive console interact() # Launch with no banner interact(quiet=True) ``` -------------------------------- ### Start better-exceptions enabled Python REPL Source: https://github.com/qix-/better-exceptions/blob/master/README.md Launch an interactive Python shell with better-exceptions enabled by running the module directly. This provides an enhanced REPL experience. ```console $ python -m better_exceptions Type "help", "copyright", "credits" or "license" for more information. (BetterExceptionsConsole) >>> ``` -------------------------------- ### Custom Exception Formatting (Python) Source: https://context7.com/qix-/better-exceptions/llms.txt Format specific exceptions programmatically without installing the global hook. This method allows for selective formatting of exceptions using `sys.exc_info()`. ```python import sys import better_exceptions try: x = 10 y = 0 z = x / y except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() formatted_exception = better_exceptions.format_exception( exc_type, exc_value, exc_traceback ) # Returns a list of formatted strings for line in formatted_exception: print(line, end='') ``` -------------------------------- ### Custom Theme Configuration (Python) Source: https://context7.com/qix-/better-exceptions/llms.txt Customize syntax highlighting colors for better-exceptions by modifying the global `THEME` dictionary. This allows for personalized visual feedback during debugging. ```python import better_exceptions # Modify global theme better_exceptions.THEME = { 'comment': lambda s: '\x1b[2;37m{}x1b[m'.format(s), 'keyword': lambda s: '\x1b[33;1m{}x1b[m'.format(s), 'builtin': lambda s: '\x1b[35;1m{}x1b[m'.format(s), 'literal': lambda s: '\x1b[31m{}x1b[m'.format(s), 'inspect': lambda s: '\x1b[36m{}x1b[m'.format(s), } better_exceptions.hook() ``` -------------------------------- ### Enhanced REPL Launch (Bash) Source: https://context7.com/qix-/better-exceptions/llms.txt Launch an interactive Python shell with better-exceptions enabled for immediate feedback directly from the command line. This provides enhanced debugging capabilities in an interactive session. ```bash $ python -m better_exceptions Type "help", "copyright", "credits" or "license" for more information. (BetterExceptionsConsole) >>> x = [1, 2, 3] >>> y = x[10] # IndexError with variable inspection ``` -------------------------------- ### Django Middleware and Logging Configuration (Python) Source: https://context7.com/qix-/better-exceptions/llms.txt Integrate better-exceptions into a Django application by adding the `BetterExceptionsMiddleware` to `settings.py` and configuring logging. This enhances exception reporting within Django views. ```python # settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'better_exceptions.integrations.django.BetterExceptionsMiddleware', # ... other middleware ] from better_exceptions.integrations.django import skip_errors_filter LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'skip_errors': { '()': 'django.utils.log.CallbackFilter', 'callback': skip_errors_filter, } }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['skip_errors'], 'class': 'logging.StreamHandler', } }, 'loggers': { 'django': { 'handlers': ['console'], } } } # In views.py from django.http import HttpResponse def my_view(request): user = request.user params = request.GET # Exceptions here will be formatted by better-exceptions result = int(params['missing_param']) return HttpResponse(result) ``` -------------------------------- ### Python: Implement Custom Exception Hook Source: https://context7.com/qix-/better-exceptions/llms.txt Demonstrates creating a custom exception hook using the ExceptionFormatter directly. This allows for advanced control over exception formatting, including custom prefixes and logging to files. ```python import sys from better_exceptions.formatter import ExceptionFormatter # Create formatter with custom settings formatter = ExceptionFormatter( colored=True, max_length=200, pipe_char='│', cap_char='└' ) def custom_excepthook(exc_type, exc_value, exc_traceback): formatted = formatter.format_exception(exc_type, exc_value, exc_traceback) # Add custom prefix to each line for line in formatted: sys.stderr.write("[ERROR] " + line) # Log to file with open('/tmp/errors.log', 'a') as f: for line in formatted: f.write(line) sys.excepthook = custom_excepthook # Test custom hook x = 100 y = None z = x + y # Will use custom formatting ``` -------------------------------- ### Python: Integrate better-exceptions with Unittest Source: https://context7.com/qix-/better-exceptions/llms.txt Patches the unittest module to format test failure tracebacks using better-exceptions. This allows for enhanced error reporting within unit tests. ```python import sys import unittest import better_exceptions def patch_unittest(self, err, test): lines = better_exceptions.format_exception(*err) if sys.version_info[0] == 2: return u"".join(lines).encode("utf-8") return "".join(lines) unittest.result.TestResult._exc_info_to_string = patch_unittest class TestMath(unittest.TestCase): def test_division(self): numerator = 10 denominator = 0 result = numerator / denominator self.assertEqual(result, 0) if __name__ == '__main__': unittest.main() ``` -------------------------------- ### Configure Django Settings for better-exceptions Source: https://github.com/qix-/better-exceptions/blob/master/README.md Integrate better-exceptions into a Django project by adding the BetterExceptionsMiddleware to settings.py and configuring the logging handler to use the skip_errors_filter. ```python # ... MIDDLEWARE = [ # ... "better_exceptions.integrations.django.BetterExceptionsMiddleware", ] # ... from better_exceptions.integrations.django import skip_errors_filter # if you don't want to override LOGGING because you want to change the default, # you can vendor Django's default logging configuration and update it for # better-exceptions. the default for Django 3.1.4 can be found here: # https://github.com/django/django/blob/3.1.4/django/utils/log.py#L13-L63 LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'skip_errors': { '()': 'django.utils.log.CallbackFilter', 'callback': skip_errors_filter, } }, 'handlers': { 'console': { 'level': 'INFO', # without the 'filters' key, Django will log errors twice: # one time from better-exceptions and one time from Django. # with the 'skip_errors' filter, we remove the repeat log # from Django, which is unformatted. 'filters': ['skip_errors'], 'class': 'logging.StreamHandler', } }, 'loggers': { 'django': { 'handlers': [ 'console', ], } } } ``` -------------------------------- ### Configure Maximum Output Length in Python Source: https://github.com/qix-/better-exceptions/blob/master/README.md Modify the MAX_LENGTH setting in better-exceptions to display the full values of variables instead of truncated ones. This is useful for debugging. ```python import better_exceptions better_exceptions.MAX_LENGTH = None ``` -------------------------------- ### Enable better-exceptions via Environment Variable Source: https://github.com/qix-/better-exceptions/blob/master/README.md Set the BETTER_EXCEPTIONS environment variable to activate better-exceptions. This needs to be done in the system's environment settings. ```bash # Linux / OSX export BETTER_EXCEPTIONS=1 ``` ```bash # Windows setx BETTER_EXCEPTIONS 1 ``` -------------------------------- ### Patch unittest for better-exceptions integration in Python Source: https://github.com/qix-/better-exceptions/blob/master/README.md Integrate better-exceptions with Python's unittest framework by monkey-patching the TestResult._exc_info_to_string method. This customizes how exceptions are formatted during test runs. ```python import sys import unittest import better_exceptions def patch(self, err, test): lines = better_exceptions.format_exception(*err) if sys.version_info[0] == 2: return u"".join(lines).encode("utf-8") return "".join(lines) unittest.result.TestResult._exc_info_to_string = patch ``` -------------------------------- ### Manually Activate better-exceptions Hook in Python Source: https://github.com/qix-/better-exceptions/blob/master/README.md Manually activate the better-exceptions hook at the beginning of a Python script. This is an alternative to setting the environment variable. ```python import better_exceptions; better_exceptions.hook() ``` -------------------------------- ### Logging Integration with better-exceptions (Python) Source: https://context7.com/qix-/better-exceptions/llms.txt Integrate better-exceptions with Python's logging module to enhance exception logs. When an exception occurs within a `logger.exception` call, it will be formatted with variable inspection. ```python import logging import better_exceptions better_exceptions.hook() logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def risky_operation(): user_id = 12345 api_key = "secret_key" data = {"items": [1, 2, 3]} try: result = data["missing_key"] except Exception: # Exception will show all local variables logger.exception("Operation failed") risky_operation() ``` -------------------------------- ### Python: Control Variable Truncation in Exceptions Source: https://context7.com/qix-/better-exceptions/llms.txt Configures better-exceptions to control the maximum length of variable values displayed in tracebacks. Setting MAX_LENGTH to None shows full values, while a numeric value truncates to that length, appending '...'. ```python import better_exceptions # Show full variable values (no truncation) better_exceptions.MAX_LENGTH = None better_exceptions.hook() def process_data(): long_string = "a" * 1000 long_list = list(range(500)) # Exception will show complete values raise Exception("Processing failed") process_data() # Set custom truncation length better_exceptions.MAX_LENGTH = 50 better_exceptions.hook() def process_more(): data = "x" * 200 # Exception will show first 50 chars + "..." raise Exception("Failed again") process_more() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.