Python: How to transform a method or a class into obsolete?

2

This time I want to learn about structures in Python packages, and I need your help again.

How to make a method or class obsolete? How to display a message in the interpreter's debugger when a method or class is no longer supported?

    
asked by anonymous 12.05.2018 / 12:57

2 answers

3

To issue the obsolete function message, use the warn or showwarning method of the #

Example:

import warnings

def funcao_obsoleta():
    # Habilita avisos de "obsoleto", que, a princípio, são ignorados
    warnings.simplefilter('always', DeprecationWarning)
    # Emite o aviso
    warnings.showwarning("Esta função é obsoleta",
        category=DeprecationWarning,
        filename=__file__,
        lineno=25
        )
    # Restaura o status dos avisos
    warnings.simplefilter('default', DeprecationWarning)
    # Corpo da função
    print("Função")
    return

funcao_obsoleta()

Output:

x.py:25: DeprecationWarning: Esta função é obsoleta
  category=DeprecationWarning,
Função

If you prefer to create a decorator :

import functools
import warnings

# Cria o decorator
def obsoleto(f):
    @functools.wraps(f)
    def deco(*args, **kwargs):
        # Emite o aviso
        warnings.simplefilter('always', DeprecationWarning)
        warnings.warn("Esta função é obsoleta", category=DeprecationWarning)
        warnings.simplefilter('default', DeprecationWarning)
        # Executa a função
        return f(*args, **kwargs)
    return deco

# Função com o decorator

@obsoleto
def funcao_obsoleta2():
    print("Função 2")
    return

funcao_obsoleta2()

Output:

x.py:11: DeprecationWarning: Esta função é obsoleta
  warnings.warn("Esta função é obsoleta", category=DeprecationWarning)
Função 2
    
12.05.2018 / 16:42
1

Another alternative would be to use a ready-made library that incorporates a decorator into your projects, such as the Deprecated library.

To install you can use pip:

pip install deprecated

and apply to your code this way:

from deprecated import deprecated

@deprecated(version='1.2.0', reason="Voce deveria usar outra função")
def some_old_function(x, y):
   return x + y
    
12.05.2018 / 16:54