2
This time I want to learn about Python package structures, and I need your help again.
How to turn a method or a class into obsolete? How to display a message in the interpreter’s Debugger, when a method or class is no longer supported?
2
This time I want to learn about Python package structures, and I need your help again.
How to turn a method or a class into obsolete? How to display a message in the interpreter’s Debugger, when a method or class is no longer supported?
3
To send the obsolete function message, use the method warn or showwarning module warnings:
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()
Exit:
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()
Exit:
x.py:11: DeprecationWarning: Esta função é obsoleta
  warnings.warn("Esta função é obsoleta", category=DeprecationWarning)
Função 2
1
Another alternative would be the use of a ready-made library that incorporates a decorator into its projects, such as the library Deprecated
to install you can use Pip:
pip install deprecated
and apply to your code in that 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
Browser other questions tagged python
You are not signed in. Login or sign up in order to post.