or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-deprecated

Python @deprecated decorator to deprecate old python classes, functions or methods.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/deprecated@1.2.x

To install, run

npx @tessl/cli install tessl/pypi-deprecated@1.2.0

index.mddocs/

Deprecated

Python @deprecated decorator to deprecate old python classes, functions or methods. This library provides comprehensive deprecation functionality with both simple warning-based decorators and advanced Sphinx integration for automatic documentation generation.

Package Information

  • Package Name: Deprecated
  • Language: Python
  • Installation: pip install Deprecated
  • Python Version: >=2.7, !=3.0., !=3.1., !=3.2., !=3.3.
  • Dependencies: wrapt < 2, >= 1.10

Core Imports

Basic deprecation decorator:

from deprecated import deprecated

Sphinx integration with documentation directives:

from deprecated.sphinx import deprecated, versionadded, versionchanged

Advanced usage with custom adapters:

from deprecated.classic import deprecated, ClassicAdapter
from deprecated.sphinx import SphinxAdapter

Warning types for custom categories (from Python's warnings module):

from warnings import DeprecationWarning, FutureWarning, PendingDeprecationWarning

Basic Usage

Simple Deprecation

from deprecated import deprecated

@deprecated
def some_old_function(x, y):
    return x + y

@deprecated
class SomeOldClass:
    pass

class SomeClass:
    @deprecated
    def some_old_method(self, x, y):
        return x + y

Deprecation with Details

from deprecated import deprecated

@deprecated(reason="use another function", version='1.2.0')
def some_old_function(x, y):
    return x + y

@deprecated(reason="This method is deprecated", version='1.3.0')
def some_old_method(self, x, y):
    return x + y

Sphinx Integration

from deprecated.sphinx import deprecated, versionadded, versionchanged

@versionadded(version='1.0', reason="This function is new")
def new_function():
    '''This function was added in version 1.0'''

@versionchanged(version='1.1', reason="This function behavior changed")
def modified_function():
    '''This function was modified in version 1.1'''

@deprecated(version='1.2', reason="This function will be removed soon")
def old_function():
    '''This function is deprecated as of version 1.2'''

Capabilities

Classic Deprecation Decorator

Simple deprecation decorator that emits DeprecationWarning when decorated functions, methods, or classes are used.

def deprecated(*args, **kwargs):
    """
    Decorator to mark functions, methods, or classes as deprecated.
    
    Parameters:
    - reason (str, optional): Reason message for deprecation
    - version (str, optional): Version when deprecated  
    - action (str, optional): Warning filter action ("default", "error", "ignore", "always", "module", "once")
    - category (Type[Warning], optional): Warning category class (default: DeprecationWarning)
    - adapter_cls (Type, optional): Custom adapter class (default: ClassicAdapter)
    - extra_stacklevel (int, optional): Additional stack levels for warnings (default: 0)
    
    Returns:
    Decorated function, method, or class
    """

Usage patterns:

  • @deprecated - Simple deprecation
  • @deprecated("reason message") - With reason string as positional argument
  • @deprecated(reason="...", version="1.2.3") - With named parameters
  • @deprecated(action="error") - With warning control

Note: The @deprecated("reason") syntax works because the function automatically detects when the first argument is a string and treats it as the reason parameter.

Classic Adapter

Base adapter class for implementing custom deprecation message formatting.

class ClassicAdapter:
    def __init__(self, reason="", version="", action=None, category=DeprecationWarning, extra_stacklevel=0):
        """
        Construct a wrapper adapter.
        
        Parameters:
        - reason (str): Reason message for deprecation
        - version (str): Version when deprecated
        - action (str): Warning filter action
        - category (Type[Warning]): Warning category class
        - extra_stacklevel (int): Additional stack levels for warnings
        """
        
    def get_deprecated_msg(self, wrapped, instance):
        """
        Get the deprecation warning message for the user.
        
        Parameters:
        - wrapped: Wrapped class or function
        - instance: The object to which the wrapped function was bound
        
        Returns:
        str: The warning message
        """
        
    def __call__(self, wrapped):
        """
        Decorate your class or function.
        
        Parameters:
        - wrapped: Wrapped class or function
        
        Returns:
        The decorated class or function
        """

Sphinx Documentation Integration

Decorators that add Sphinx directives to docstrings for automatic documentation generation.

def versionadded(reason="", version="", line_length=70):
    """
    Insert a "versionadded" directive in docstring.
    
    Parameters:
    - reason (str): Reason message documenting the addition
    - version (str): Version when added (required)
    - line_length (int): Max line length for directive text (default: 70)
    
    Returns:
    SphinxAdapter: Decorator adapter that modifies docstring when applied
    """

def versionchanged(reason="", version="", line_length=70):
    """
    Insert a "versionchanged" directive in docstring.
    
    Parameters:
    - reason (str): Reason message documenting the modification
    - version (str): Version when changed (required)
    - line_length (int): Max line length for directive text (default: 70)
    
    Returns:
    SphinxAdapter: Decorator adapter that modifies docstring when applied
    """

def deprecated(reason="", version="", line_length=70, **kwargs):
    """
    Insert a "deprecated" directive in docstring and emit deprecation warning.
    
    Parameters:
    - reason (str): Reason message documenting the deprecation
    - version (str): Version when deprecated (required for Sphinx directives)
    - line_length (int): Max line length for directive text (default: 70)
    - **kwargs: Additional keyword arguments:
        - action (str): Warning filter action
        - category (Type[Warning]): Warning category
        - extra_stacklevel (int): Additional stack levels
        - directive (str): Override directive type (default: "deprecated")
        - adapter_cls (Type): Override adapter class (default: SphinxAdapter)
    
    Returns:
    Callable: Decorator function that applies SphinxAdapter with deprecation warning
    
    Raises:
    - ValueError: If version parameter is not provided (required for Sphinx directives)
    """

Sphinx Adapter

Advanced adapter that extends ClassicAdapter to add Sphinx directives to docstrings.

class SphinxAdapter(ClassicAdapter):
    def __init__(self, directive, reason="", version="", action=None, category=DeprecationWarning, extra_stacklevel=0, line_length=70):
        """
        Construct a Sphinx wrapper adapter.
        
        Parameters:
        - directive (str): Sphinx directive ("versionadded", "versionchanged", "deprecated")
        - reason (str): Reason message
        - version (str): Version (required - cannot be empty for Sphinx directives)
        - action (str): Warning filter action
        - category (Type[Warning]): Warning category (must be imported from warnings)
        - extra_stacklevel (int): Additional stack levels
        - line_length (int): Max line length for directive text (default: 70)
        
        Raises:
        - ValueError: If version parameter is empty or not provided
        """
        
    def get_deprecated_msg(self, wrapped, instance):
        """
        Get deprecation warning message with Sphinx cross-referencing syntax stripped.
        
        This method first calls the parent ClassicAdapter.get_deprecated_msg() to get
        the base warning message, then uses regex to strip Sphinx cross-reference
        syntax (like :role:`foo` and :domain:role:`foo`) for cleaner warnings.
        
        Parameters:
        - wrapped: Wrapped class or function
        - instance: The object to which the wrapped function was bound
        
        Returns:
        str: The warning message with Sphinx cross-reference syntax removed
        """
        
    def __call__(self, wrapped):
        """
        Add Sphinx directive to docstring and decorate class or function.
        
        Parameters:
        - wrapped: Wrapped class or function
        
        Returns:
        The decorated class or function with modified docstring
        """

Advanced Usage Examples

Custom Adapter

import inspect
from deprecated.classic import ClassicAdapter, deprecated

class MyClassicAdapter(ClassicAdapter):
    def get_deprecated_msg(self, wrapped, instance):
        if instance is None:
            if inspect.isclass(wrapped):
                fmt = "The class {name} is deprecated."
            else:
                fmt = "The function {name} is deprecated."
        else:
            if inspect.isclass(instance):
                fmt = "The class method {name} is deprecated."
            else:
                fmt = "The method {name} is deprecated."
        if self.reason:
            fmt += " ({reason})"
        if self.version:
            fmt += " -- Deprecated since version {version}."
        return fmt.format(name=wrapped.__name__, 
                         reason=self.reason or "", 
                         version=self.version or "")

@deprecated(reason="use another function", adapter_cls=MyClassicAdapter)
def some_old_function(x, y):
    return x + y

Warning Control

from deprecated import deprecated

# Raise error instead of warning
@deprecated(action="error")
def critical_old_function():
    pass

# Ignore deprecation warnings
@deprecated(action="ignore")
def silent_old_function():
    pass

# Show warning once per module
@deprecated(action="once")
def one_time_warning_function():
    pass

Custom Warning Categories

from deprecated import deprecated
from warnings import DeprecationWarning, FutureWarning, PendingDeprecationWarning

class MyDeprecationWarning(DeprecationWarning):
    pass

@deprecated(category=MyDeprecationWarning)
def function_with_custom_warning():
    pass

# Can also use built-in warning types
@deprecated(category=FutureWarning)
def function_with_future_warning():
    pass

@deprecated(category=PendingDeprecationWarning)
def function_with_pending_warning():
    pass

Stack Level Control

from deprecated import deprecated

def wrapper_function():
    @deprecated(extra_stacklevel=1)
    def inner_function():
        pass
    return inner_function

# The warning will point to the caller of wrapper_function
# instead of the call to inner_function

Error Handling

The decorators may raise the following exceptions:

  • ValueError: When required parameters are missing (e.g., version parameter required for Sphinx directives)
  • TypeError: When decorator is applied to unsupported object types (non-callable, non-class objects)

The decorated functions emit warnings of the specified category:

  • DeprecationWarning: Default warning category for deprecated functionality (must be imported from warnings module)
  • FutureWarning: Alternative warning category for future deprecations
  • PendingDeprecationWarning: For deprecations that are not yet active
  • Custom Warning Categories: User-defined warning classes for specialized handling

Types

# Warning filter actions
ActionType = Literal["default", "error", "ignore", "always", "module", "once"]

# Sphinx directive types  
DirectiveType = Literal["versionadded", "versionchanged", "deprecated"]

# Base adapter interface
class AdapterProtocol:
    def __init__(self, reason: str = "", version: str = "", action: ActionType = None, 
                 category: Type[Warning] = DeprecationWarning, extra_stacklevel: int = 0): ...
    def get_deprecated_msg(self, wrapped: Callable, instance: Any) -> str: ...
    def __call__(self, wrapped: Callable) -> Callable: ...