นักตกแต่งใน python มาตรฐาน lib (@deprecated โดยเฉพาะ)


128

ฉันต้องทำเครื่องหมายกิจวัตรว่าเลิกใช้แล้ว แต่ดูเหมือนว่าไม่มีตัวตกแต่งห้องสมุดมาตรฐานสำหรับการเลิกใช้งาน ฉันทราบถึงสูตรอาหารและโมดูลคำเตือน แต่คำถามของฉันคือเหตุใดจึงไม่มีผู้ตกแต่งห้องสมุดมาตรฐานสำหรับงานนี้ (ทั่วไป)

คำถามเพิ่มเติม: มีมัณฑนากรมาตรฐานในไลบรารีมาตรฐานหรือไม่?


13
ตอนนี้มีแพ็คเกจการเลิกใช้งาน
muon

11
ฉันเข้าใจวิธีการทำ แต่มาที่นี่เพื่อรับข้อมูลเชิงลึกว่าเหตุใดจึงไม่อยู่ใน std lib (ตามที่ฉันคิดว่าเป็นกรณีของ OP) และไม่เห็นคำตอบที่ดีสำหรับคำถามจริง
SwimBikeRun

4
เหตุใดจึงเกิดขึ้นบ่อยครั้งที่คำถามจะได้รับคำตอบมากมายที่ไม่แม้แต่จะพยายามตอบคำถามและเพิกเฉยต่อสิ่งต่างๆเช่น "ฉันรู้สูตรอาหาร" มันน่าโมโห!
Catskul

1
@Catskul เพราะจุดเน็ตปลอม.
Stefano Borini

1
คุณสามารถใช้Deprecated Library
Laurent LAPORTE

คำตอบ:


59

นี่คือตัวอย่างบางส่วนที่แก้ไขจากที่ Leandro อ้างถึง:

import warnings
import functools

def deprecated(func):
    """This is a decorator which can be used to mark functions
    as deprecated. It will result in a warning being emitted
    when the function is used."""
    @functools.wraps(func)
    def new_func(*args, **kwargs):
        warnings.simplefilter('always', DeprecationWarning)  # turn off filter
        warnings.warn("Call to deprecated function {}.".format(func.__name__),
                      category=DeprecationWarning,
                      stacklevel=2)
        warnings.simplefilter('default', DeprecationWarning)  # reset filter
        return func(*args, **kwargs)
    return new_func

# Examples

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

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

เนื่องจากในล่ามบางตัววิธีแก้ปัญหาแรกที่เปิดเผย (โดยไม่มีการจัดการตัวกรอง) อาจส่งผลให้เกิดการระงับคำเตือน


14
ทำไมไม่ใช้functools.wrapsแทนที่จะตั้งชื่อและเอกสารแบบนั้น
Maximilian

1
@ Maximilian: แก้ไขเพื่อเพิ่มสิ่งนั้นเพื่อบันทึกผู้คัดลอกในอนาคตของรหัสนี้ไม่ให้ทำผิดเช่นกัน
Eric

17
ฉันไม่ชอบผลข้างเคียง (การเปิด / ปิดฟิลเตอร์) ไม่ใช่งานของมัณฑนากรที่จะตัดสินใจเรื่องนี้
Kentzo

1
การเปิดและปิดตัวกรองอาจทำให้เกิดbugs.python.org/issue29672
gerrit

4
ไม่ตอบคำถามที่แท้จริง
Catskul

45

นี่คือวิธีแก้ปัญหาอื่น:

มัณฑนากรนี้ ( โรงงานมัณฑนากรในความเป็นจริง) ช่วยให้คุณสามารถบอกเหตุผลได้ นอกจากนี้ยังมีประโยชน์อื่น ๆ อีกมากมายที่จะช่วยให้นักพัฒนาที่จะวินิจฉัยปัญหาโดยการให้แหล่งที่มาของชื่อไฟล์และหมายเลขบรรทัด

แก้ไข : รหัสนี้ใช้คำแนะนำของ Zero: แทนที่warnings.warn_explicitบรรทัดโดยwarnings.warn(msg, category=DeprecationWarning, stacklevel=2)ซึ่งพิมพ์ไซต์เรียกฟังก์ชันแทนที่จะเป็นไซต์นิยามฟังก์ชัน ทำให้การดีบักง่ายขึ้น

แก้ไข 2 : เวอร์ชันนี้อนุญาตให้ผู้พัฒนาระบุข้อความ "เหตุผล" ที่เป็นทางเลือก

import functools
import inspect
import warnings

string_types = (type(b''), type(u''))


def deprecated(reason):
    """
    This is a decorator which can be used to mark functions
    as deprecated. It will result in a warning being emitted
    when the function is used.
    """

    if isinstance(reason, string_types):

        # The @deprecated is used with a 'reason'.
        #
        # .. code-block:: python
        #
        #    @deprecated("please, use another function")
        #    def old_function(x, y):
        #      pass

        def decorator(func1):

            if inspect.isclass(func1):
                fmt1 = "Call to deprecated class {name} ({reason})."
            else:
                fmt1 = "Call to deprecated function {name} ({reason})."

            @functools.wraps(func1)
            def new_func1(*args, **kwargs):
                warnings.simplefilter('always', DeprecationWarning)
                warnings.warn(
                    fmt1.format(name=func1.__name__, reason=reason),
                    category=DeprecationWarning,
                    stacklevel=2
                )
                warnings.simplefilter('default', DeprecationWarning)
                return func1(*args, **kwargs)

            return new_func1

        return decorator

    elif inspect.isclass(reason) or inspect.isfunction(reason):

        # The @deprecated is used without any 'reason'.
        #
        # .. code-block:: python
        #
        #    @deprecated
        #    def old_function(x, y):
        #      pass

        func2 = reason

        if inspect.isclass(func2):
            fmt2 = "Call to deprecated class {name}."
        else:
            fmt2 = "Call to deprecated function {name}."

        @functools.wraps(func2)
        def new_func2(*args, **kwargs):
            warnings.simplefilter('always', DeprecationWarning)
            warnings.warn(
                fmt2.format(name=func2.__name__),
                category=DeprecationWarning,
                stacklevel=2
            )
            warnings.simplefilter('default', DeprecationWarning)
            return func2(*args, **kwargs)

        return new_func2

    else:
        raise TypeError(repr(type(reason)))

คุณสามารถใช้มัณฑนากรนี้ฟังก์ชั่น , วิธีการและการเรียน

นี่คือตัวอย่างง่ายๆ:

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


class SomeClass(object):
    @deprecated("use another method")
    def some_old_method(self, x, y):
        return x + y


@deprecated("use another class")
class SomeOldClass(object):
    pass


some_old_function(5, 3)
SomeClass().some_old_method(8, 9)
SomeOldClass()

คุณจะได้รับ:

deprecated_example.py:59: DeprecationWarning: Call to deprecated function or method some_old_function (use another function).
  some_old_function(5, 3)
deprecated_example.py:60: DeprecationWarning: Call to deprecated function or method some_old_method (use another method).
  SomeClass().some_old_method(8, 9)
deprecated_example.py:61: DeprecationWarning: Call to deprecated class SomeOldClass (use another class).
  SomeOldClass()

แก้ไข 3:มัณฑนากรนี้เป็นส่วนหนึ่งของไลบรารีที่เลิกใช้แล้ว:

เวอร์ชันเสถียรใหม่ v1.2.10 🎉


6
ใช้งานได้ดี - ฉันชอบแทนที่warn_explicitบรรทัดwarnings.warn(msg, category=DeprecationWarning, stacklevel=2)ที่พิมพ์ไซต์เรียกฟังก์ชันมากกว่าไซต์นิยามฟังก์ชัน ทำให้การดีบักง่ายขึ้น
ศูนย์

สวัสดีผมอยากจะใช้โค้ดของคุณในห้องสมุด GPLv3 ได้รับอนุญาต คุณยินดีที่จะเปลี่ยนรหัสของคุณใหม่ภายใต้ GPLv3 หรือใบอนุญาตที่ได้รับอนุญาตเพิ่มเติมเพื่อที่ฉันจะสามารถทำได้อย่างถูกกฎหมายหรือไม่?
gerrit


1
@LaurentLAPORTE ฉันรู้ CC-BY-SO ไม่อนุญาตให้ใช้งานภายใน GPLv3 (เนื่องจากบิตเหมือนกัน) ซึ่งเป็นสาเหตุที่ฉันถามว่าคุณยินดีที่จะปล่อยรหัสนี้โดยเฉพาะเพิ่มเติมภายใต้ใบอนุญาตที่เข้ากันได้กับ GPL หรือไม่ ถ้าไม่เป็นเช่นนั้นฉันจะไม่ใช้รหัสของคุณ
gerrit

2
ไม่ตอบคำถามที่แท้จริง
Catskul

15

ตามที่ muon แนะนำคุณสามารถติดตั้งdeprecationแพ็คเกจนี้ได้

deprecationห้องสมุดมีdeprecatedมัณฑนากรและfail_if_not_removedมัณฑนากรสำหรับการทดสอบของคุณ

การติดตั้ง

pip install deprecation

ตัวอย่างการใช้งาน

import deprecation

@deprecation.deprecated(deprecated_in="1.0", removed_in="2.0",
                        current_version=__version__,
                        details="Use the bar function instead")
def foo():
    """Do some stuff"""
    return 1

ดูhttp://deprecation.readthedocs.io/สำหรับเอกสารฉบับเต็ม


4
ไม่ตอบคำถามที่แท้จริง
Catskul

1
หมายเหตุPyCharmไม่รู้จักสิ่งนี้
cz

12

ฉันเดาว่าเหตุผลก็คือโค้ด Python ไม่สามารถประมวลผลแบบคงที่ได้ (เหมือนกับที่ทำกับคอมไพเลอร์ C ++) คุณจะไม่ได้รับคำเตือนเกี่ยวกับการใช้บางสิ่งก่อนที่จะใช้งานจริง ฉันไม่คิดว่าเป็นความคิดที่ดีที่จะสแปมผู้ใช้สคริปต์ของคุณด้วยข้อความจำนวนมาก "คำเตือน: ผู้พัฒนาสคริปต์นี้กำลังใช้ API ที่เลิกใช้งานแล้ว"

อัปเดต:แต่คุณสามารถสร้างมัณฑนากรซึ่งจะเปลี่ยนฟังก์ชันดั้งเดิมเป็นฟังก์ชันอื่น ฟังก์ชั่นใหม่จะทำเครื่องหมาย / ตรวจสอบสวิตช์เพื่อบอกว่าฟังก์ชันนี้ถูกเรียกใช้แล้วและจะแสดงข้อความเฉพาะเมื่อเปลี่ยนสวิตช์เป็นสถานะเปิด และ / หรือเมื่อออกจากระบบอาจพิมพ์รายการฟังก์ชันที่เลิกใช้งานทั้งหมดที่ใช้ในโปรแกรม


3
และคุณควรจะสามารถที่จะบ่งบอกเลิกเมื่อฟังก์ชั่นนำเข้าจากโมดูล มัณฑนากรจะเป็นเครื่องมือที่เหมาะสมสำหรับสิ่งนั้น
Janusz Lenar

@JanuszLenar คำเตือนนั้นจะแสดงแม้ว่าเราจะไม่ได้ใช้ฟังก์ชันที่เลิกใช้แล้วก็ตาม แต่ฉันเดาว่าฉันสามารถอัปเดตคำตอบด้วยคำใบ้ได้
ony

8

คุณสามารถสร้างไฟล์ utils

import warnings

def deprecated(message):
  def deprecated_decorator(func):
      def deprecated_func(*args, **kwargs):
          warnings.warn("{} is a deprecated function. {}".format(func.__name__, message),
                        category=DeprecationWarning,
                        stacklevel=2)
          warnings.simplefilter('default', DeprecationWarning)
          return func(*args, **kwargs)
      return deprecated_func
  return deprecated_decorator

จากนั้นนำเข้าตัวตกแต่งการเลิกใช้งานดังต่อไปนี้:

from .utils import deprecated

@deprecated("Use method yyy instead")
def some_method()"
 pass

ขอบคุณฉันใช้สิ่งนี้เพื่อส่งผู้ใช้ไปยังตำแหน่งที่ถูกต้องแทนที่จะแสดงข้อความเลิกใช้งาน!
German Attanasio

3
ไม่ตอบคำถามที่แท้จริง
Catskul

2

UPDATE: ฉันคิดว่าดีกว่าเมื่อเราแสดง DeprecationWarning เพียงครั้งแรกสำหรับแต่ละบรรทัดรหัสและเมื่อเราสามารถส่งข้อความ:

import inspect
import traceback
import warnings
import functools

import time


def deprecated(message: str = ''):
    """
    This is a decorator which can be used to mark functions
    as deprecated. It will result in a warning being emitted
    when the function is used first time and filter is set for show DeprecationWarning.
    """
    def decorator_wrapper(func):
        @functools.wraps(func)
        def function_wrapper(*args, **kwargs):
            current_call_source = '|'.join(traceback.format_stack(inspect.currentframe()))
            if current_call_source not in function_wrapper.last_call_source:
                warnings.warn("Function {} is now deprecated! {}".format(func.__name__, message),
                              category=DeprecationWarning, stacklevel=2)
                function_wrapper.last_call_source.add(current_call_source)

            return func(*args, **kwargs)

        function_wrapper.last_call_source = set()

        return function_wrapper
    return decorator_wrapper


@deprecated('You must use my_func2!')
def my_func():
    time.sleep(.1)
    print('aaa')
    time.sleep(.1)


def my_func2():
    print('bbb')


warnings.simplefilter('always', DeprecationWarning)  # turn off filter
print('before cycle')
for i in range(5):
    my_func()
print('after cycle')
my_func()
my_func()
my_func()

ผลลัพธ์:

before cycle
C:/Users/adr-0/OneDrive/Projects/Python/test/unit1.py:45: DeprecationWarning: Function my_func is now deprecated! You must use my_func2!
aaa
aaa
aaa
aaa
aaa
after cycle
C:/Users/adr-0/OneDrive/Projects/Python/test/unit1.py:47: DeprecationWarning: Function my_func is now deprecated! You must use my_func2!
aaa
C:/Users/adr-0/OneDrive/Projects/Python/test/unit1.py:48: DeprecationWarning: Function my_func is now deprecated! You must use my_func2!
aaa
C:/Users/adr-0/OneDrive/Projects/Python/test/unit1.py:49: DeprecationWarning: Function my_func is now deprecated! You must use my_func2!
aaa

Process finished with exit code 0

เราสามารถคลิกที่เส้นทางคำเตือนและไปที่บรรทัดใน PyCharm


2
ไม่ตอบคำถามที่แท้จริง
Catskul

0

การเพิ่มคำตอบนี้โดย Steven Vascellaro :

หากคุณใช้ Anaconda ให้ติดตั้งdeprecationแพ็คเกจก่อน:

conda install -c conda-forge deprecation 

จากนั้นวางสิ่งต่อไปนี้ที่ด้านบนของไฟล์

import deprecation

@deprecation.deprecated(deprecated_in="1.0", removed_in="2.0",
                    current_version=__version__,
                    details="Use the bar function instead")
def foo():
    """Do some stuff"""
    return 1

ดูhttp://deprecation.readthedocs.io/สำหรับเอกสารฉบับเต็ม


4
ไม่ตอบคำถามที่แท้จริง
Catskul
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.