9

It's possible to mark deprecated classes in Python/PyCharm like this:

class Foo:
    def __init__(self):
        warnings.warn('Use Bar instead.', DeprecationWarning)

Any code trying to instantiate Foo now will be appropriately marked by PyCharm as Foo().

However, just inheriting the class won't:

class Baz(Foo):
    pass

Is there any way to have the declaration of Baz marked with a deprecation warning in any way?

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Possible duplicate of [How to warn about class (name) deprecation](http://stackoverflow.com/questions/9008444/how-to-warn-about-class-name-deprecation) – Jerzyk Jul 01 '16 at 11:37
  • @deceze are you seeing it's still possible to mark classes deprecated in the latest versions of pycharm? Your post is the only one I've been able to find even mentioning it, but can't seem to make it work. – Marcel Wilson Jan 25 '22 at 20:46

1 Answers1

0

You can use a metaclass to accomplish this. In Python 2.7:

import warnings

def deprecated_metaclass(message):
    class DeprecatedMetaclass(type):
        def __init__(cls, name, bases, dct):
            if not hasattr(cls, '__metaclass__'):
                cls.__metaclass__ = DeprecatedMetaclass
            if any(getattr(base, '__metaclass__', None) == DeprecatedMetaclass
                    for base in bases):
                warnings.warn(message, DeprecationWarning, stacklevel=2)
            super(DeprecatedMetaclass, cls).__init__(name, bases, dct)

class Foo(object):
    __metaclass__ = deprecated_metaclass('Use Bar instead.')

class Bar(Foo):
    pass

Note that outside of PyCharm you might not see anything because deprecation warnings are off by default.

In Python 3, change Foo to:

class Foo(metaclass=deprecated_metaclass('Use Bar instead.')):
    pass
Luke Moore
  • 685
  • 5
  • 7