-2

I am trying to deprecate property of class.

class A:
   def __init__(self,
   variable1: int,
   ##to be deprecated
   variable2: int )
   {....}

Expected behaviour: If user tries to use variable 2 he should get warning that its deprecated.

Isha Nema
  • 289
  • 5
  • 16
  • 5
    "`variable2`" is a required positional argument. How would the user not use it? – Brian61354270 Sep 03 '21 at 02:05
  • 3
    Related (but possibly outdated): [decorators in the python standard lib (@deprecated specifically)](https://stackoverflow.com/questions/2536307/decorators-in-the-python-standard-lib-deprecated-specifically) – Brian61354270 Sep 03 '21 at 02:06
  • 1
    Can you also provide a sample use-case for class `A`? What does "*use variable 2*" mean and when exactly should it show the warning? – Gino Mempin Sep 03 '21 at 02:11

2 Answers2

6

You can just give it a None default and make sure it's not set:

import warnings

class A:
    def __init__(
        self,
        variable1,
        variable2=None,
    ):

        if variable2 is not None:
            warnings.warn(
                "variable2 is deprecated", DeprecationWarning
            )

Works with kwargs:

>>> A(1, variable2=123)
<ipython-input-4-e722737121fe>:12: DeprecationWarning: variable2 is deprecated

Works with positional args:

>>> A(1, 123)
<ipython-input-4-e722737121fe>:12: DeprecationWarning: variable2 is deprecated
TayTay
  • 6,882
  • 4
  • 44
  • 65
4

You can implement variable2 as a property.

import warnings

class A:
    def __init__(self, variable1: int, variable2: int):
        self.variable1 = variable1
        self._variable2 = variable2

    @property
    def variable2(self):
        warnings.warn('The use of variable2 is deprecated.', DeprecationWarning)
        return self._variable2

    @variable2.setter
    def variable2(self, value: int):
        warnings.warn('The use of variable2 is deprecated.', DeprecationWarning)
        self._variable2 = value
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45