The Python Oracle

How to ignore deprecation warnings in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Civilization

--

Chapters
00:00 Question
00:24 Accepted answer (Score 143)
00:56 Answer 2 (Score 284)
01:09 Answer 3 (Score 225)
01:47 Answer 4 (Score 53)
02:26 Thank you

--

Full question
https://stackoverflow.com/questions/8791...

Accepted answer links:
[warnings]: https://docs.python.org/3/library/warnin...
[int]: http://docs.python.org/3.0/library/funct...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #warnings #deprecated

#avk47



ANSWER 1

Score 326


You should just fix your code but just in case,

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning) 



ANSWER 2

Score 245


I had these:

/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/persisted/sob.py:12:
DeprecationWarning: the md5 module is deprecated; use hashlib instead import os, md5, sys

/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/python/filepath.py:12:
DeprecationWarning: the sha module is deprecated; use the hashlib module instead import sha

Fixed it with:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings("ignore",category=DeprecationWarning)
    import md5, sha

yourcode()

Now you still get all the other DeprecationWarnings, but not the ones caused by:

import md5, sha



ACCEPTED ANSWER

Score 154


From documentation of the warnings module:

 #!/usr/bin/env python -W ignore::DeprecationWarning

If you're on Windows: pass -W ignore::DeprecationWarning as an argument to Python. Better though to resolve the issue, by casting to int.

(Note that in Python 3.2, deprecation warnings are ignored by default.)




ANSWER 4

Score 33


I found the cleanest way to do this (especially on windows) is by adding the following to C:\Python26\Lib\site-packages\sitecustomize.py:

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)

Note that I had to create this file. Of course, change the path to python if yours is different.