Sunday, July 17, 2022

[FIXED] How to throw DeprecationWarning when users are importing a module?

Issue

So I looked for a bit but I wasn't finding anything that talked about my issue, so I decided to open a new question.

My question is, how can I throw a DeprecationError in python if a user were to import a module that has been renamed?

Quick Example of what I would be trying to accomplish:

>>> import foo.bar as foobar
DeprecationWarning: import foo.bar is deprecated and will be removed in a 
future release, please use import foo.bar2 in order to access the goodness 
of foo bar

I tried to something like this in the bar file (for this example):

bar.py

import stuff

warnings.warn("import foo.bar is deprecated and will be removed in a future release, please use import foo.bar2 in order to access the goodness of foo bar", DeprecationWarning)

But unfortunately this did not work when I ran a test script and imported the module. Is there something that I am missing? How can I run the code in the module on loading of the module?


Solution

You need to set out a filter for the warnings or use -Wd switch with interpreter call. By default the deprecuation warnings are switched off.

See an example at http://www.jaggedverge.com/2016/09/deprecation-warnings-in-python/



Answered By - Evgeny
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.