36

How to declare a module deprecated in python?

I want a warning to be printed whenever a particular module is imported or any of its functions are called.

3
  • 1
    Add print "Deprecated" to __init__ or add a decorator that does the same. Commented May 7, 2015 at 6:32
  • docs.python.org/2/library/warnings.html Commented May 7, 2015 at 6:36
  • 1
    @ForceBru: How are you going to add a decorator to a module? And where are you going to find its __init__ method? Commented May 7, 2015 at 6:39

2 Answers 2

36

You want to warn with a DeprecationWarning.

Exactly how you call it doesn't matter that much, but the stdlib has a standard pattern for deprecated modules, like this:

# doc string, top-level comments, imports, __all__ =

import warnings
warnings.warn("the spam module is deprecated", DeprecationWarning,
              stacklevel=2)

# normal module code

See the 2.7 sets source for an example.

Sign up to request clarification or add additional context in comments.

2 Comments

I have used this piece of code in my init.py of a specific module on which I want to display as deprecated. Its not working, neither its erring out. the function and class of that module can be easily accessible.
Deprecation does not make something stop working. It gives you advance warning that it will stop working in a future version.
-1

Were you not happy with warnings.warn, to print to your console, you could follow this solution, which uses the logging module for Python.

However, in my experience, you need to add a logging.basicConfig() command before your logging.warning function call, so I'd suggest something like:

import logging
logging.basicConfig()
logging.warning(msg="this is a warning")

1 Comment

Why do you think someone would be unhappy with warnings, but find this acceptable? Don't use basicConfig in a module; configuration is for the script that uses your module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.